🚚 Move Zeroes – Python (In-Place Solution)
Hi All,
Today I solved a popular problem: Move all zeroes to the end of the array while maintaining the order of non-zero elements.
📌 Problem Statement
Given an array nums, move all 0s to the end while:
- Maintaining the relative order of non-zero elements
- Performing the operation in-place (no extra array)
🔍 Examples
Example 1:
nums = [0, 1, 0, 3, 12]
Output:
[1, 3, 12, 0, 0]
Example 2:
nums = [0]
Output:
[0]
💡 Approach
🔹 Two Pointer Technique (Optimal)
👉 Idea:
- Use a pointer
jto track position for non-zero elements - Traverse array with
i - Swap non-zero elements forward
🧠 Step-by-Step Logic
- Initialize
j = 0 - Traverse array:
- If element is not zero:
- Swap
nums[i]withnums[j] - Increment
j
- Swap
- If element is not zero:
💻 Python Code
def moveZeroes(nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
🔍 Dry Run
For:
nums = [0, 1, 0, 3, 12]
Steps:
- Swap 1 → [1, 0, 0, 3, 12]
- Swap 3 → [1, 3, 0, 0, 12]
- Swap 12 → [1, 3, 12, 0, 0]
Final Output:
[1, 3, 12, 0, 0]
🖥️ Sample Output
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Input: [0]
Output: [0]
⚡ Complexity Analysis
- Time Complexity: O(n) ✅
- Space Complexity: O(1) ✅
🧠 Why this is important?
- Uses two pointer technique
- Maintains order (stable)
- Common pattern in array problems
✅ Conclusion
This problem helped me understand:
- In-place array manipulation
- Efficient element shifting
- Two pointer strategy
🚀 A must-know problem for beginners and interviews!
Top comments (0)