Fetching latest headlines…
Move Zeros
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’March 22, 2026

Move Zeros

0 views0 likes0 comments
Originally published byDev.to

Introduction

Moving zeros in an array is a common problem that helps in understanding array manipulation and two-pointer techniques.

Problem Statement

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

Approach (Two-Pointer Technique)

We use two pointers:

  1. Initialize a pointer j = 0 (position for non-zero elements)
  2. Traverse the array using index i
  3. If element is non-zero:
    • Swap arr[i] with arr[j]
    • Increment j
  4. Continue until the end

Python Code


python
def move_zeros(arr):
    j = 0

    for i in range(len(arr)):
        if arr[i] != 0:
            arr[i], arr[j] = arr[j], arr[i]
            j += 1

    return arr

# Example
arr = [0, 1, 0, 3, 12]
print("Result:", move_zeros(arr))


## Input
 [0,1,0,3,4]

## Output
 [1,3,4,0,0]

Comments (0)

Sign in to join the discussion

Be the first to comment!