Easy
Move Zeroes
- Time limit
- 1 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Two Pointers
Description
Description
Given an integer array nums, move all 0s to the end of the array while maintaining the relative order of the non-zero elements.
The non-zero elements must appear in the result in the same order as in the input. The zeroes, which are moved to the end, are identical to one another, so their internal order does not matter.
Return the rearranged array. The input may contain no zeroes, in which case the order is unchanged.
Examples
Example 1
- Input:
nums = [0, 1, 0, 3, 12] - Output:
[1, 3, 12, 0, 0] - Explanation: The non-zero values
1,3,12keep their relative order, and both zeroes are pushed to the end.
Example 2
- Input:
nums = [1, 2, 3] - Output:
[1, 2, 3] - Explanation: There are no zeroes, so nothing moves.
Example 3
- Input:
nums = [0, 0, 1]
Constraints
0 <= nums.length <= 100000-1000000000 <= nums[i] <= 1000000000- The relative order of the non-zero elements must be preserved.
- The total number of elements (including zeroes) must remain unchanged.
Sample cases
3Sample 1
Input
nums = [0,1,0,3,12]
Expected output
[1,3,12,0,0]
Sample 2
Input
nums = [1,2,3]
Expected output
[1,2,3]
Skills and languages
Patterns
- Two Pointers
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer