Move Zeroes
Description
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 1:
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Explanation: Move 0s to end while keeping [1, 3, 12] in their relative order.
Example 2:
Input: nums = [0]
Output: [0]
Explanation: Single zero stays in place.
Example 3:
Input: nums = [1, 2, 3]
Output: [1, 2, 3]
Explanation: No zeros to move.
Constraints
1 <= nums.length <= 10^4-2^31 <= nums[i] <= 2^31 - 1
Complexity
Show Complexity
- Time:
O(n) - Space:
O(1)
Hints
Show Hints
- Pattern
- Two pointers: slow (write position) and fast (read position)
- Approach
- Use slow pointer for next non-zero position. Iterate with fast pointer, when non-zero found, write to slow position and increment slow. Fill remaining with zeros.
- Complexity
- Single pass - move non-zeros to front, fill rest with zeros
Solutions
Show PY Solution
def solution(nums):
insert_pos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[insert_pos] = nums[insert_pos], nums[i]
insert_pos += 1
# i = 0
# j = 1
#
# while i < len(nums) - 1 and j < len(nums):
# if nums[i] == 0 and nums[j] != 0:
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# j += 1
# elif nums[i] == 0 and nums[j] == 0:
# j += 1
# elif nums[i] != 0:
# i += 1
# j += 1
return nums