Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions algorithms/arrays/move_zeros.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@
The time complexity of the below algorithm is O(n).
"""


# False == 0 is True
def move_zeros(array):
result = []
zeros = 0

for i in array:
if i == 0 and type(i) != bool: # not using `not i` to avoid `False`, `[]`, etc.
# Check for numeric zeros but exclude boolean False
# False and other falsy values (like [], '') are NOT treated as zeros.
if i == 0 and not isinstance(i, bool):
zeros += 1
else:
result.append(i)

# Append zeros to the end without allocating another temporary list
for _ in range(zeros):
result.append(0)

result.extend([0] * zeros)
return result


print(move_zeros([False, 1, 0, 1, 2, 0, 1, 3, "a"]))