Date: 2026-06-06
Time: 18:09
move-zeroes/solution.pyThis file solves LeetCode 283 - Move Zeroes. It owns exactly one responsibility: rearranging an integer list in-place so that all zeros move to the end while the relative order of non-zero elements is preserved.
moveZeroes(nums: list[int]) -> None — The sole function. It mutates nums in-place and returns nothing. The contract matches LeetCode's expected signature: the caller inspects the modified list, not a return value.
The algorithm uses the two-pointer / snowball pattern:
insert_pos is the slow pointer — it tracks where the next non-zero element should land.i is the fast pointer — it scans every element sequentially.When nums[i] != 0, the values at insertpos and i are swapped, then insertpos advances. This is a swap-based variant rather than the overwrite-then-fill approach. The swap is always safe: when insertpos == i, it's a no-op self-swap; when insertpos < i, the element at insert_pos is guaranteed to be zero (it was either originally zero or was swapped there by a previous iteration).
Imports: None — pure standard Python, no external or stdlib imports.
Imported by: The "Imported By" list in the prompt is misleading — those are test files from *other* problems that happen to share a common test harness or import mechanism. The direct consumer is move-zeroes/test_solution.py.
1. Initialize insert_pos = 0.
2. Iterate i from 0 to len(nums) - 1.
3. On each non-zero nums[i], swap nums[insertpos] with nums[i] and increment insertpos.
4. After the loop, positions [0, insertpos) hold all non-zero values in original order; positions [insertpos, len(nums)) are all zeros.
Single pass, O(n) time, O(1) space.
nums[0:insertpos] contains exactly the non-zero elements seen so far, in their original relative order, and nums[insertpos:i] contains only zeros.n swaps total (each non-zero element is swapped at most once).None. The function trusts its caller to pass a valid list[int]. Empty lists and all-zero lists work correctly — the loop body simply never executes or never triggers a swap, respectively. This is consistent with LeetCode's contract where inputs are guaranteed valid.