Problem
Move Zeroes
You are given an integer array nums.
Your task is to move all 0s to the end while maintaining the relative order of non-zero elements.
The operation must be done in-place, without using extra space.
Input: [0, 1, 0, 3, 12] → Output: [1, 3, 12, 0, 0]
Input: [0] → Output: [0]
Approach
The idea is to shift all non-zero elements forward and fill the remaining positions with zeros.
Steps:
- Use a pointer insert_pos to track where the next non-zero element should go
- Traverse the array:
- If the element is non-zero, place it at insert_pos and move the pointer forward
- After traversal, fill the rest of the array with 0s
This keeps the order intact and avoids extra space.
Complexity:
Time Complexity: O(n)
Space Complexity: O(1)
def moveZeroes(nums):
insert_pos = 0
for num in nums:
if num != 0:
nums[insert_pos] = num
insert_pos += 1
for i in range(insert_pos, len(nums)):
nums[i] = 0
return nums
nums = [0, 1, 0, 3, 12]
print(moveZeroes(nums))
Top comments (0)