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:
- Initialize a pointer
j = 0(position for non-zero elements) - Traverse the array using index
i - If element is non-zero:
- Swap arr[i] with arr[j]
- Increment j
- 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]
πΊπΈ
More news from United StatesUnited States
NORTH AMERICA
Related News
CBS News Shutters Radio Service After Nearly a Century
5h ago
White House Unveils National AI Policy Framework To Limit State Power
5h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
5h ago
Microsoft Says It Is Fixing Windows 11
5h ago
NASA's Hubble Unexpectedly Catches Comet Breaking Up
5h ago