DEV Community

Sri Mahalakshmi
Sri Mahalakshmi

Posted on

Moving Zeroes to the End of an Array Using Two Pointer Technique in Python

Problem Explanation

Given an integer array nums, your task is to move all 0s to the end of the array while maintaining the relative order of non-zero elements.

Important:

  • You must do this in-place
  • Do not create a new array

Example:

  • Input: nums = [0, 1, 0, 3, 12]
    Output: [1, 3, 12, 0, 0]

  • Input: nums = [0]
    Output: [0]


Method Used: Two Pointer Technique

We use:

  • One pointer to track position for non-zero elements
  • Another pointer to traverse the array

Why This Method?

  • Time complexity: O(n)
  • Space complexity: O(1)
  • Maintains order of non-zero elements
  • Efficient and simple

Python Code with Explanation

class Solution:
    def moveZeroes(self, nums):
Enter fullscreen mode Exit fullscreen mode

Defines the function (in-place modification, no return needed).


        insert_pos = 0
Enter fullscreen mode Exit fullscreen mode

insert_pos keeps track of where the next non-zero element should go.


        for i in range(len(nums)):
Enter fullscreen mode Exit fullscreen mode

Loop through each element using index i.


            if nums[i] != 0:
Enter fullscreen mode Exit fullscreen mode

Check if the current element is non-zero.


                nums[insert_pos], nums[i] = nums[i], nums[insert_pos]
Enter fullscreen mode Exit fullscreen mode

Swap the non-zero element with the element at insert_pos.


                insert_pos += 1
Enter fullscreen mode Exit fullscreen mode

Move insert_pos forward.


Complete Code

class Solution:
    def moveZeroes(self, nums):
        insert_pos = 0

        for i in range(len(nums)):
            if nums[i] != 0:
                nums[insert_pos], nums[i] = nums[i], nums[insert_pos]
                insert_pos += 1
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Example

Input:

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

Steps:

  • Move non-zero elements forward
  • Shift zeros to the end

Output:

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

Time and Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Key Takeaway

The Two Pointer Technique efficiently moves all zeroes to the end while preserving the order of non-zero elements, all in a single pass.


Top comments (0)