MOVE ZEROES TO END
Move Zeroes to End – Two Pointer Approach
Introduction
In this problem, we are given an array and need to move all the zeroes to the end while maintaining the relative order of non-zero elements.
The important constraint is that the operation must be done in-place, without using extra space.
Problem Statement
Given an array nums[], move all 0’s to the end while:
Maintaining the order of non-zero elements
Not using extra space
Example
Input:
nums = [0, 1, 0, 3, 12]
Output:
[1, 3, 12, 0, 0]Solution Code
class Solution {
public void moveZeroes(int[] nums) {
int j = 0; // position for next non-zero element
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j++;
}
}
}
}Approach Used: Two Pointer Technique
Idea
We use two pointers:
i= scans the arrayj= keeps track of where the next non-zero element should go
How It Works
Initialize
j = 0Traverse array using
iIf
nums[i]is not zero:Swap
nums[i]withnums[j]Increment
j
Continue until the end
Why This Approach Was Chosen
Works in one pass (O(n))
Maintains relative order of non-zero elements
Uses constant space (O(1))
Efficient and simple logic
Alternative Approaches
Using extra array
Copy non-zero elements first, then add zeros
Uses extra spaceShift elements manually
More complex and less efficient
Why Two Pointer?
Because it satisfies both constraints:
In-place
Maintains order
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Important Observation
Swapping ensures non-zero elements move forward
Zeroes automatically move to the end
Order of non-zero elements remains unchanged
Conclusion
The two-pointer approach provides an efficient and clean solution to move zeroes to the end of the array. It satisfies all constraints by working in-place and maintaining order, making it the optimal choice for this problem.
Comments
Post a Comment