Skip to content

Instantly share code, notes, and snippets.

@afternoon
Created September 1, 2015 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afternoon/9b6552fa5924d8105428 to your computer and use it in GitHub Desktop.
Save afternoon/9b6552fa5924d8105428 to your computer and use it in GitHub Desktop.
Given an array of numbers (1,2,3,8,0,2,2,0,10), move all 0s to the right end and all other numbers to the left while keeping relative order of non-zero numbers. Has to be linear in time and in-place.
def separate_zeroes(nums):
'''
Given an array of numbers (1,2,3,8,0,2,2,0,10), move all 0s to the right end and all other numbers to the left while keeping relative order of non-zero numbers. Has to be linear in time and in-place.
>>> separate_zeroes([1, 2, 3, 8, 0, 2, 2, 0, 10])
[1, 2, 3, 8, 2, 2, 10, 0, 0]
>>> separate_zeroes([1, 1, 1, 0, 1, 0, 0, 1])
[1, 1, 1, 1, 1, 0, 0, 0]
>>> separate_zeroes([0])
[0]
>>> separate_zeroes([0, 0, 1])
[1, 0, 0]
>>> separate_zeroes([0, 0, 0, 1, 0, 0, 0])
[1, 0, 0, 0, 0, 0, 0]
'''
num_zeroes = 0
zero_to_swap = None
for i in range(0, len(nums)):
if nums[i] == 0:
if zero_to_swap is None:
zero_to_swap = i
else:
if zero_to_swap is not None:
nums[zero_to_swap] = nums[i]
nums[i] = 0
zero_to_swap = i
return nums
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment