Introduction
Rearranging elements in an array while maintaining order is a common problem in programming. One such important problem is moving all zeroes to the end of the array without disturbing the order of non-zero elements.
This problem helps in understanding in-place operations and efficient array manipulation.
Problem Statement
Given an integer array nums, move all 0s to the end while maintaining the relative order of non-zero element
Example
Input:
nums = [0, 1, 0, 3, 12]
Output:
[1, 3, 12, 0, 0]
Approach: Two-Pointer Method
We use:
-
jposition to place the next non-zero element
Steps:
- Traverse the array
- If element is non-zero:
- Swap it with position
j - Increment
j
Python Implementation
def move_zeroes(nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1
return nums
# Example usage
nums = [0, 1, 0, 3, 12]
print(move_zeroes(nums))
Step-by-Step Example
For:
[0, 1, 0, 3, 12]
- i = 0 then skip (0)
- i = 1 then swap = [1, 0, 0, 3, 12]
- i = 3 then swap = [1, 3, 0, 0, 12]
- i = 4 then swap = [1, 3, 12, 0, 0]
Final result: [1, 3, 12, 0, 0]
Key Points
- Maintains order of non-zero elements
- Works in-place
- Efficient single traversal
- Common interview problem
Conclusion
The Move Zeroes problem is a great example of using the two-pointer technique to efficiently rearrange elements in an array. It avoids unnecessary operations and ensures optimal performance.
Understanding this pattern will help in solving many similar array manipulation problems.
Top comments (0)