AceYourInterviews
Checking sign-in…

19. Move Zeroes

EasyStable read/write compaction then zero fill

Move all zero values to the end of nums in place. Keep the original relative order of all nonzero values.

The required result is the changed array; the function returns no value.

Example 1

Input

[0,1,0,3,12]

Output

[1,3,12,0,0]

Explanation: The surviving sequence 1,3,12 retains encounter order.

Example 2

Input

[0,-2,0,-1]

Output

[-2,-1,0,0]

Explanation: Negative values are preserved, not filtered.

Constraints

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1
  • Move zeroes in place and preserve the relative order of nonzero values.
Hints
Hint 1

Treat nonzeros as the subsequence to retain.

Hint 2

Can a write position ever get ahead of the read position?

Hint 3

Compact nonzeros first; fill the remaining suffix with zero.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Stable compaction then suffix fill

[0,1,0,3,12]
[1,3,12,0,0]