DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 78: Python Move Zeros to End – O(n) In-Place Two-Pointer Technique for Array Reordering (LeetCode #283 Guide)

Welcome to Day 78 of the #80DaysOfChallenges journey! This intermediate challenge solves the move all zeros to the end of an array while preserving non-zero order problem (LeetCode #283), using a two-pointer approach to swap or overwrite in O(n) time with O(1) space, modifying the list in-place without extras. It combines read/write pointers for efficient filtering, a common pattern in array manipulation for data cleaning or compression. If you're advancing from basic arrays to in-place algos or prepping for interviews with reorder problems, this "Python move zeros" script demonstrates a function that's optimal, clean, and easy to adapt for other filtering like move negatives or duplicates.


💡 Key Takeaways from Day 78: Move Zeros Function

This task features an in-place function that uses a write pointer to place non-zeros at front, then fills back with zeros. It's a filter pattern: separate non-zeros, pad zeros. We'll detail: function with write pointer init, loop for non-zero placement, and back fill with zeros, main input.

1. Function Design: Write Pointer for Non-Zero Position

The move_zeros function modifies nums in-place:

def move_zeros(nums: list[int]) -> None:
    """Modify the list in-place by moving zeros to the end."""
    write = 0    # position to write next non-zero
Enter fullscreen mode Exit fullscreen mode

Write starts at 0, tracks where to place next non-zero.

2. Loop Processing: Place Non-Zeros Forward

Core loop scans:

    # move non-zero elements forward
    for num in nums:
        if num != 0:
            nums[write] = num
            write += 1
Enter fullscreen mode Exit fullscreen mode

If non-zero, place at write, increment. Skips zeros, packs non-zeros at front.

3. Back Fill: Zero the Remaining Positions

After loop, fill tail:

    # fill remaining positions with zeros
    for i in range(write, len(nums)):
        nums[i] = 0
Enter fullscreen mode Exit fullscreen mode

From write to end, set 0. For [0,1,0,3,12]: non-zeros to [1,3,12,0,0], then zero tail [1,3,12,0,0].

Main reads nums, calls, prints modified.


🎯 Summary and Reflections

This move zeros uses write pointer for in-place pack. It reinforced:

  • Two-pointer filter: Read all, write non-matches.
  • In-place efficiency: O(n) time, O(1) space.
  • No extras: Modifies original, saves memory.

Reflections: Similar to remove element. For stable, use similar.

Advanced Alternatives: List comp non-zeros + zeros len. Pointer swap version. Your reorder trick? Share!


🚀 Next Steps and Resources

Day 78 reordered arrays efficiently. In #80DaysOfChallenges? Move other? Post!

Top comments (0)