DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Move Zeroes – Python (In-Place Solution)

🚚 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]
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 3, 12, 0, 0]
Enter fullscreen mode Exit fullscreen mode

Example 2:

nums = [0]
Enter fullscreen mode Exit fullscreen mode

Output:

[0]
Enter fullscreen mode Exit fullscreen mode

💡 Approach

🔹 Two Pointer Technique (Optimal)

👉 Idea:

  • Use a pointer j to track position for non-zero elements
  • Traverse array with i
  • Swap non-zero elements forward

🧠 Step-by-Step Logic

  1. Initialize j = 0
  2. Traverse array:
    • If element is not zero:
      • Swap nums[i] with nums[j]
      • Increment j

💻 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
Enter fullscreen mode Exit fullscreen mode

🔍 Dry Run

For:

nums = [0, 1, 0, 3, 12]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

🖥️ Sample Output

Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]

Input: [0]
Output: [0]
Enter fullscreen mode Exit fullscreen mode

⚡ 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)