283. Move Zeroes
Asked at 37Bloomberg67Microsoft65Meta63Amazon61Google60Apple59EPAM Systems95tcs80Cognizant73Yandex73Infosys68LTI100Sigmoid100Chewy89oyo88Wix87NetApp79VK77Qualcomm76Accenture75Zoho74Capgemini73SAP73AMD69Zomato62IBM55ServiceNow55Nvidia55Walmart Labs53josh technology50Oracle45Adobe44PayPal42Cisco37Goldman Sachs36Uber30TikTok26
Problem
Move every 0 in nums to the end, in place, keeping the non-zero values in their original relative order.
Example: [0,1,0,3,12] → [1,3,12,0,0]
Constraints: no copy of the array; follow-up: minimise the number of writes.
Slow pointer k = next slot for a non-zero. Swap each non-zero into k; zeros drift to the end while relative order is kept.
Complexity: O(n) time, O(1) space.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
k = 0
for i in range(len(nums)):
if nums[i]:
nums[k], nums[i] = nums[i], nums[k]
k += 1
a = [0, 1, 0, 3, 12]; Solution().moveZeroes(a)
assert a == [1, 3, 12, 0, 0]
a = [0]; Solution().moveZeroes(a)
assert a == [0]
a = [1, 0, 0, 2]; Solution().moveZeroes(a)
assert a == [1, 2, 0, 0]
class Solution {
public void moveZeroes(int[] nums) {
int k = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] != 0) { int t = nums[k]; nums[k++] = nums[i]; nums[i] = t; }
}
}
func moveZeroes(nums []int) {
k := 0
for i := range nums {
if nums[i] != 0 {
nums[k], nums[i] = nums[i], nums[k]
k++
}
}
}