Skip to content

Instantly share code, notes, and snippets.

@karmatr0n
Created June 23, 2023 13:46
Show Gist options
  • Save karmatr0n/1bab0ddaebaff6d80b426f223f5030f9 to your computer and use it in GitHub Desktop.
Save karmatr0n/1bab0ddaebaff6d80b426f223f5030f9 to your computer and use it in GitHub Desktop.
Move all zeros to the end
def move_zeros(nums)
return nums if nums.empty?
left = 0
right = nums.length - 1
while left < right do
if nums[left] == 0
nums[left], nums[right] = nums[right], nums[left]
right -= 1
else
left += 1
end
end
nums
end
nums = [0, 1, 0, 0, 0, 0, 1, 2, 3, 4, 0, 1, 5, 7 ]
result = move_zeros(nums)
puts result.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment