2dbi

Move zeroes

viaLeetCode

Problem Move all zeros in an integer array to the end while preserving the relative order of non-zero elements — in place, single pass.

Input / Output

  • Input: int array nums. Output: nums mutated in place.

Constraints

  • n up to 10^4; O(n) time, O(1) space; minimize writes (a common probe).

Example

  • [0,1,0,3,12] → [1,3,12,0,0].

Expected approach

  • Write-pointer sweep: copy each non-zero to nums[w++]; afterwards fill nums[w..] with zeros — two logical phases, one pass over data. Swap variant (swap nums[i] with nums[w] when non-zero) keeps it single-phase and write-light when zeros are rare. O(n)/O(1). Edge probes: all zeros, no zeros, stability requirement ruling out two-pointer-from-both-ends.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account