DEV Community

JAYA SRI J
JAYA SRI J

Posted on

Moves Zeroes

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

Note that you must do this in-place without making a copy of the array.

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

Example 2:
Input: nums = [0]
Output: [0]

Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1

SOLUTIONS:
Move Zeroes (LeetCode 283) – Optimal In-Place Approach
Problem Statement

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

The operation must be done in-place
No extra array should be used

Key Idea: Two Pointers

This solution uses two pointers:

l tracks the position where the next non-zero element should be placed
r iterates through the array

Whenever a non-zero element is found at index r, it is swapped with the element at index l, and l is incremented.

Code Implementation
Writing

class Solution:
def moveZeroes(self, nums: List[int]) -> None:
     l = 0
     for r in range(len(nums)):
        if nums[r]:
           nums[l], nums[r] = nums[r], nums[l]
           l += 1
    return nums
Enter fullscreen mode Exit fullscreen mode

Example Walkthrough

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

Step-by-step process:

At index 0: value is 0 → skip
At index 1: value is 1 → swap with index 0 → array becomes [1, 0, 0, 3, 12]
At index 2: value is 0 → skip
At index 3: value is 3 → swap with index 1 → array becomes [1, 3, 0, 0, 12]
At index 4: value is 12 → swap with index 2 → array becomes [1, 3, 12, 0, 0]

Final output:

[1, 3, 12, 0, 0]
Why This Works

  1. All non-zero elements are moved forward as they are encountered. Since the traversal is from left to right and elements are placed in the next available position, the relative order of non-zero elements is preserved. Zeroes automatically shift to the remaining positions at the end.
  2. Complexity Analysis 3.Time Complexity: O(n), since the array is traversed once
  3. Space Complexity: O(1), since no additional space is used
  4. Key Insight

The condition:
if nums[r]:
is equivalent to:
if nums[r] != 0:

Top comments (0)