Algorithm-Day04-Move-Zeroes-lc#283
π§© Problem Description
Given an integer array nums
, move all 0
βs to the end of it while maintaining the relative order of the non-zero elements.
You must do this in-place without making a copy of the array.
Example:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
π‘ Naive Idea (Two-Pass Write)
- Create a new array and copy all non-zero values into it, then append zeroes.
- β Correct but β not in-place. So itβs invalid.
π‘ Optimal In-Place Approach (Two Pointers)
We use the two-pointer technique:
- Use a
nonZeroIndex
to track the next position to place a non-zero. - Traverse the array:
- If current element is not 0, write it to
nonZeroIndex
, then incrementnonZeroIndex
.
- If current element is not 0, write it to
- Finally, fill the remaining elements from
nonZeroIndex
to end with 0.
This is done in-place and only requires one pass + cleanup.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n) β single pass for placement + fill
- Space Complexity: O(1) β in-place manipulation
βοΈ Summary
- The key is to use two pointers to separate writing and reading.
- Remember: βIn-placeβ means no extra array.
- Common interview problem β focus on efficiency and clarity.
This pattern of tracking write position separately is widely used in array transformations.