about summary refs log tree commit diff
path: root/scratch/facebook/move-zeroes-to-end.py
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2020-11-15T13·51+0000
committerWilliam Carroll <wpcarro@gmail.com>2020-11-15T13·51+0000
commitc8330adfcb2bf86c4ad35091d805f35603bc55e0 (patch)
tree29592e1326c9238cffd1233ca2cf4291c6df2383 /scratch/facebook/move-zeroes-to-end.py
parent09cd819a70b0b647960f0d8f55d628c78779592d (diff)
Solve "Move Zeroes to End"
Write a function to modify an array of integers in-place such that all of the
zeroes in the array are at the end, and the order of the other integers is not
changed.
Diffstat (limited to 'scratch/facebook/move-zeroes-to-end.py')
-rw-r--r--scratch/facebook/move-zeroes-to-end.py26
1 files changed, 26 insertions, 0 deletions
diff --git a/scratch/facebook/move-zeroes-to-end.py b/scratch/facebook/move-zeroes-to-end.py
new file mode 100644
index 000000000000..aa9f73d6f11d
--- /dev/null
+++ b/scratch/facebook/move-zeroes-to-end.py
@@ -0,0 +1,26 @@
+def move_zeroes_to_end(xs):
+    n_zeroes = 0
+    for x in xs:
+        if x == 0:
+            n_zeroes += 1
+
+    i = 0
+    while i < len(xs) - 1:
+        if xs[i] == 0:
+            j = i + 1
+            while j < len(xs) and xs[j] == 0:
+                j += 1
+            if j >= len(xs):
+                break
+            xs[i], xs[j] = xs[j], xs[i]
+        i += 1
+    # add zeroes to the end
+    for i in range(n_zeroes):
+        xs[len(xs) - 1 - i] = 0
+
+xs = [1, 2, 0, 3, 4, 0, 0, 5, 0]
+print(xs)
+move_zeroes_to_end(xs)
+assert xs == [1, 2, 3, 4, 5, 0, 0, 0, 0]
+print(xs)
+print("Success!")