DSA problem
Move Zeroes
Given an integer array nums, move all 0's to the end of the array while maintaining the relative order of the non-zero elements.
You must do this in-place without making a copy of the array. For example, given [0,1,0,3,12] the array should become [1,3,12,0,0].
Try to minimize the total number of operations. The optimal solution uses two pointers and performs at most one swap per element.
Examples
Example 1
Input:
nums = [0,1,0,3,12]Output:
[1,3,12,0,0]Explanation: The non-zero elements 1, 3, 12 keep their relative order and the two zeros are pushed to the end.
Example 2
Input:
nums = [0]Output:
[0]Explanation: A single zero stays in place.
Constraints
- 1 <= nums.length <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.