Move Zeroes — LeetCode 283 Python Solution
- Problem
- #283
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 += 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{nums} |
| Space | O(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.