Created
January 24, 2019 21:50
-
-
Save flavienbwk/d7d56df1c7e30516ca446da4c46bb032 to your computer and use it in GitHub Desktop.
Coding interview problem : move all zeros present in the array to the end, and return the SAME array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Move all zeros present in the array to the end, and return the SAME array. | |
# | |
# I: [0, 1, 2, 0, 3, 0] | |
# O: [1, 2, 3, 0, 0, 0] | |
# | |
# No empty array. | |
# No negative numbers. | |
def shiftZeros(array): | |
i = 0 | |
while (i < len(array)): | |
if (array[i] == 0): | |
while (len(array) > i + 1 and array[i + 1] != 0): | |
array[i] = array[i + 1] | |
array[i + 1] = 0 | |
i += 1 | |
i += 1 | |
else: | |
memo = i | |
while (i > 0 and array[i - 1] == 0): | |
array[i - 1] = array[i] | |
array[i] = 0 | |
i -= 1 | |
i = memo + 1 | |
i += 1 | |
return array | |
print shiftZeros([0, 1, 2, 0, 3, 0, 6]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment