↓Skip to main content
  1. LeetCode/

LeetCode 283: Move Zeroes

·1 min· ·
LeetCode Easy Array Two-Pointers
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted ×2 → Wrong Answer ×2 → Accepted ×2

Approach
#

left is where the next non-zero value goes (Two Pointers Template 5). On a non-zero nums[right], swap it with nums[left] and advance left. Non-zero values keep their order and zeros end up at the back.

My Attempts
#

It passed in 2022; a 2025 rewrite placed left += 1 outside the if, advancing every step, so nothing moved: [0, 1] stayed [0, 1].

Solution
#

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        left = 0
        for right in range(len(nums)):
            if nums[right] != 0:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • left += 1 belongs inside the if, advancing only after writing a non-zero value.

Interview Explanation
#

left marks where the next non-zero value goes; each non-zero value is swapped there and left advances, pushing zeros back. Time O(n), space O(1).

Related

LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 344: Reverse String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 344 note: swap with two pointers and move inward to reverse in place