NeetCode #183LC-283EasyTwo Pointers
← Back to All Problems#183 · #283 · Move Zeroes(移动零)
📌 Problem Statement & Constraints
Given an integer array
nums, move all 0s to the end while maintaining the relative order of the non-zero elements, in place. Constraints: 1 <= nums.length <= 10^4, -2^31 <= nums[i] <= 2^31 - 1.💡 Core Algorithmic Approaches
- Use a write pointer
kfor the next non-zero slot. Scan with a read pointer and copy every non-zero value tonums[k]. - After the scan, fill the remaining slots from
kto the end with zeros. - This preserves the relative order of the non-zero elements, which a swap-based approach with a two-ended pointer would not.
- An alternative is to swap the non-zero value into position
kimmediately, which achieves the same result in one pass.
💻 Benchmark Python3 Implementation
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
k = 0 # next slot for a non-zero value
for i in range(len(nums)):
if nums[i] != 0:
nums[k] = nums[i]
k += 1
for i in range(k, len(nums)):
nums[i] = 0 # pad the tail with zeros
# One-pass swap variant (also preserves order)
class Solution2:
def moveZeroes(self, nums: List[int]) -> None:
k = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[k], nums[i] = nums[i], nums[k]
k += 1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one or two passes.
💾 Space Complexity
O(1): in place.
⚠️ Interview Pitfalls & Follow-ups
- Using
nums.remove(0)in a loop: O(n^2) and the indices shift underneath you. - Swapping zeros to the front: the relative order of the non-zero elements must be preserved, so zeros go to the end.
- Forgetting the padding pass: the slots after
kstill hold stale values, so they must be zeroed (or, in the swap variant, they are already zeros). - Comparing with
is 0: use== 0, sinceiscompares identity.