DEV Community

Sruthika Ramachandran
Sruthika Ramachandran

Posted on

Move Zeores

**Introduction

**
In array manipulation problems, we often need to rearrange elements while maintaining their order.

This problem focuses on moving all 0s to the end of the array while keeping the relative order of non-zero elements unchanged.

Problem Statement

Given an integer array nums, move all 0s to the end while maintaining the order of non-zero elements.

Constraints:

  • Perform the operation in-place
  • Do not create a copy of the array

Examples

Example 1:
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]

Example 2:
Input: [0]
Output: [0]

Intuition

  • Move all non-zero elements forward
  • Fill remaining positions with 0s

This ensures:

  • Order is maintained
  • No extra space is used

Approach

We use a pointer j to track the position where the next non-zero element should go.

Algorithm Steps

  1. Initialize j = 0
  2. Traverse array using i:
  • If nums[i] != 0:

    • Swap nums[i] with nums[j]
    • Increment j

End result: all non-zero elements are shifted forward, zeros move to end

Code (Python)

def move_zeroes(nums):
    j = 0

    for i in range(len(nums)):
        if nums[i] != 0:
            nums[i], nums[j] = nums[j], nums[i]
            j += 1

Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

For [0, 1, 0, 3, 12]:

  • Skip 0
  • Move 1 → [1, 0, 0, 3, 12]
  • Skip 0
  • Move 3 → [1, 3, 0, 0, 12]
  • Move 12 → [1, 3, 12, 0, 0]

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Conclusion

The Move Zeroes problem is a great example of in-place array manipulation using two pointers.

Top comments (0)