DEV Community

Lokeshwaran S
Lokeshwaran S

Posted on

Move Zeroes - CA13

My Thinking and Approach


Introduction

In this problem, I was given an array of integers and asked to move all zeroes to the end of the array.

The important condition is that the relative order of non-zero elements should be maintained.


Problem Statement

  • Given an array of integers nums

  • Move all 0’s to the end

  • Conditions:

    • Maintain relative order of non-zero elements
    • Perform operation in-place
    • Do not use extra space

My Initial Thought

At first, I considered:

  • Creating a new array
  • Adding all non-zero elements
  • Then adding zeroes at the end

But this approach uses extra space.


Key Observation

Instead of using extra space:

  • I can shift all non-zero elements to the front
  • Then fill the remaining positions with zeroes

Optimized Approach

I decided to use a pointer to track position of non-zero elements.

Logic:

  • Traverse the array
  • Place non-zero elements at correct position
  • Fill remaining positions with zeroes

My Approach (Step-by-Step)

  1. Initialize a pointer pos = 0
  2. Traverse the array:
  • If element is not zero
    → place it at index pos
    → increment pos

    1. After traversal:
  • Fill remaining elements with 0


Code (Python)

Below is the implementation clearly separated inside a code block:

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

        for i in range(len(nums)):
            if nums[i] != 0:
                nums[pos] = nums[i]
                pos += 1

        for i in range(pos, len(nums)):
            nums[i] = 0
Enter fullscreen mode Exit fullscreen mode

Example Walkthrough

Input:

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

Steps:

  • Move non-zero elements → [1, 3, 12, _, _]
  • Fill remaining with zeroes → [1, 3, 12, 0, 0]

Output:

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

Complexity Analysis

Type Complexity
Time Complexity O(n)
Space Complexity O(1)

Key Takeaways

  • In-place modification is important
  • Two-pass solution is efficient
  • Maintaining order is key

Conclusion

This problem helped me understand how to rearrange elements efficiently while maintaining order and without using extra space.


Top comments (0)