DEV Community

Mohith
Mohith

Posted on

Move Zeroes-CA13

My Thinking and Approach

Introduction

In this problem, I was given an integer array and asked to move all the 0s to the end while maintaining the relative order of the non-zero elements.

At first glance, it looked simple. But the constraint that the operation must be done in-place (without using extra space) made me think more carefully about the solution.


Problem Statement

  • Move all 0s to the end of the array
  • Maintain the order of non-zero elements
  • Do it in-place (no extra array allowed)

My Initial Approach

Initially, I thought of a straightforward method:

  • Create a new array
  • Add all non-zero elements
  • Then append all zeros at the end

But this approach uses extra space, which violates the problem constraint.

So I needed a more optimized solution.


Optimized Approach (Two Pointer Technique)

To solve this efficiently, I used the two-pointer approach.

Idea

  • Use one pointer i to traverse the array
  • Use another pointer j to track the position where the next non-zero element should be placed

Steps

  1. Initialize j = 0
  2. Traverse the array using i
  3. If nums[i] != 0:
  • Swap nums[i] with nums[j]
  • Increment j
    1. Continue till the end of the array

Code (Java)

class Solution {
    public void moveZeroes(int[] nums) {
        int j = 0;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                j++;
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Example

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

Step-by-step execution:

  • i = 0 → value = 0 → skip
  • i = 1 → value = 1 → swap with index

Top comments (0)