Skip to content
LEETFLIX

Easy · compact non-zeroes. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 283. Move Zeroes. The copyrighted prompt is on LeetCode. This page is a working compact non-zeroes for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[0, 1, 0, 3, 12]

Output

[1, 3, 12, 0, 0]

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Write non-zeroes, then fill zeros

w is the next free slot. Copy every non-zero forward, then zero out the tail.

Relative order of non-zeroes is preserved because we copy them in the order we see them.

Algorithm

  1. Scan left to right; write each non-zero at w and increment w.
  2. Fill nums[w:] with zeros.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def moveZeroes(self, nums: list[int]) -> list[int]:        w = 0        for x in nums:            if x != 0:                nums[w] = x                w += 1        for i in range(w, len(nums)):            nums[i] = 0        return nums
Watch this run

03

Interactive walkthrough

Playing “Write non-zeroes, then fill zeros”. Edit the input, hit Run, then scrub.

Approach: Write non-zeroes, then fill zeros

Loading animation…