In-place Move Zeros to End of List in Python

Moving zeros to the end of a list while maintaining the relative order of non-zero elements is a common array manipulation problem. This can be solved efficiently using a two-pointer technique that modifies the list in-place with O(1) extra space.

The algorithm works by using one pointer to track the position for non-zero elements and another to iterate through the entire list.

Algorithm Steps

The approach follows these steps:

  • Use a pointer k to track the position for the next non-zero element
  • Iterate through the list and move all non-zero elements to the front
  • Fill the remaining positions with zeros

Example

Here's the implementation of the in-place zero movement algorithm:

def move_zeros_to_end(nums):
    if len(nums) == 0:
        return []
    
    k = 0  # Position for next non-zero element
    
    # Move all non-zero elements to the front
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[k] = nums[i]
            k += 1
    
    # Fill remaining positions with zeros
    for j in range(k, len(nums)):
        nums[j] = 0
    
    return nums

# Test the function
numbers = [2, 0, 1, 4, 0, 5, 6, 4, 0, 1, 7]
result = move_zeros_to_end(numbers)
print(result)
[2, 1, 4, 5, 6, 4, 1, 7, 0, 0, 0]

How It Works

Let's trace through the algorithm with the input [2, 0, 1, 4, 0, 5]:

def move_zeros_step_by_step(nums):
    print(f"Initial: {nums}")
    k = 0
    
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[k] = nums[i]
            print(f"Move {nums[i]} to position {k}: {nums}")
            k += 1
    
    for j in range(k, len(nums)):
        nums[j] = 0
        print(f"Set position {j} to 0: {nums}")
    
    return nums

# Trace the algorithm
test_list = [2, 0, 1, 4, 0, 5]
move_zeros_step_by_step(test_list)
Initial: [2, 0, 1, 4, 0, 5]
Move 2 to position 0: [2, 0, 1, 4, 0, 5]
Move 1 to position 1: [2, 1, 1, 4, 0, 5]
Move 4 to position 2: [2, 1, 4, 4, 0, 5]
Move 5 to position 3: [2, 1, 4, 5, 0, 5]
Set position 4 to 0: [2, 1, 4, 5, 0, 5]
Set position 5 to 0: [2, 1, 4, 5, 0, 0]

Time and Space Complexity

Aspect Complexity Explanation
Time O(n) Single pass through the array
Space O(1) Only uses constant extra space

Alternative: Optimized Two-Pointer Approach

For even better performance, we can swap elements instead of overwriting:

def move_zeros_optimized(nums):
    left = 0  # Pointer for non-zero position
    
    for right in range(len(nums)):
        if nums[right] != 0:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
    
    return nums

# Test the optimized approach
numbers = [0, 1, 0, 3, 12]
result = move_zeros_optimized(numbers)
print(result)
[1, 3, 12, 0, 0]

Conclusion

The two-pointer technique efficiently moves zeros to the end while preserving the order of non-zero elements. This in-place solution achieves O(n) time complexity with O(1) space complexity, making it optimal for large datasets.

Updated on: 2026-03-25T10:25:09+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements