DEV Community

VARUN
VARUN

Posted on

CA 13 - Move Zeros


Move Zeroes – Clear Explanation (LeetCode 283)

Problem Statement
Given an array nums.

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


Approach: Two Pointers
Idea:

  • Use pointer j to track position for next non-zero
  • Traverse array with pointer i

Algorithm

  1. Initialize j = 0
  2. Loop through array using i
  3. If nums[i] != 0:
  • Swap nums[i] and nums[j]
  • Increment j

Input:

nums = [0,1,0,3,12]
output:
| i | j | Array State |
| - | - | ------------ |
| 0 | 0 | [0,1,0,3,12] |
| 1 | 0 | [1,0,0,3,12] |
| 2 | 1 | [1,0,0,3,12] |
| 3 | 1 | [1,3,0,0,12] |
| 4 | 2 | [1,3,12,0,0] |


💻 Code (Python)

python
class Solution(object):
def moveZeroes(self, nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]

j += 1

Top comments (0)