Skip to content

283. Move Zeroes 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  void moveZeroes(vector<int>& nums) {
    int i = 0;
    for (const int num : nums)
      if (num != 0)
        nums[i++] = num;

    while (i < nums.size())
      nums[i++] = 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public void moveZeroes(int[] nums) {
    int i = 0;
    for (final int num : nums)
      if (num != 0)
        nums[i++] = num;

    while (i < nums.length)
      nums[i++] = 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def moveZeroes(self, nums: list[int]) -> None:
    j = 0
    for num in nums:
      if num != 0:
        nums[j] = num
        j += 1

    for i in range(j, len(nums)):
      nums[i] = 0