Move Zeroes — LeetCode 283 Python Solution

EasyArrayTwo Pointers
Problem
#283
Reading time
2 min

The problem

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.

Example

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

Python solution

Python
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        k = 0
        for i, x in enumerate(nums):
            if x:
                nums[k], nums[i] = nums[i], nums[k]
                k += 1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 283. Move Zeroes is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 283. Move Zeroes?
LeetCode 283. Move Zeroes is rated Easy on LeetCode.
What is the time complexity of LeetCode 283. Move Zeroes?
The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 283. Move Zeroes?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 283. Move Zeroes cover?
LeetCode 283. Move Zeroes is tagged Array and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview