283. Move Zeroes
easyIn-place, move all zeros in an array to the end while keeping the relative order of non-zero elements. A two-pointer warm-up that tests partition-by-predicate intuition.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
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.
Constraints
1 <= nums.length <= 10^4-2^31 <= nums[i] <= 2^31 - 1
Examples
Example 1
nums = [0,1,0,3,12][1,3,12,0,0]Example 2
nums = [0][0]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Copying to a new array is easy but the problem requires in-place. What's a one-pass strategy?
Hint 2
Imagine a slow pointer that tracks 'where the next non-zero should land' and a fast pointer that scans the array.
Hint 3
When fast finds a non-zero, swap nums[fast] and nums[slow], then advance slow. Zeros get pushed right naturally as you swap.
Solution approach
Reveal approach
Two pointers, both starting at index 0. The fast pointer scans every element. The slow pointer marks the next slot that should receive a non-zero. When fast finds a non-zero, swap nums[fast] and nums[slow] (or assign if fast > slow) and advance slow. After the scan, every position before slow is non-zero (in original order) and every position from slow onward is zero. One pass, O(1) extra space.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- two-pointers
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Meta
- Amazon
- Microsoft
- Bloomberg
Practice these live with InterviewChamp.AI
Drill Move Zeroes and Arrays problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →