Python Program to Move Zeros to End of Array
arr = [x for x in arr if x != 0] + [0] * arr.count(0).Examples
How to Think About It
Algorithm
Code
def move_zeros_to_end(arr): non_zero = [x for x in arr if x != 0] zeros = [0] * arr.count(0) return non_zero + zeros # Example usage arr = [0, 1, 0, 3, 12] result = move_zeros_to_end(arr) print(result)
Dry Run
Let's trace the example [0, 1, 0, 3, 12] through the code
Extract non-zero elements
non_zero = [1, 3, 12]
Count zeros
zeros = [0, 0] because there are 2 zeros
Combine lists
result = [1, 3, 12] + [0, 0] = [1, 3, 12, 0, 0]
| Step | non_zero list | zeros list | Result |
|---|---|---|---|
| 1 | [1, 3, 12] | ||
| 2 | [1, 3, 12] | [0, 0] | |
| 3 | [1, 3, 12, 0, 0] |
Why This Works
Step 1: Filter non-zero elements
We use a list comprehension with if x != 0 to keep only the numbers that are not zero, preserving their order.
Step 2: Count zeros
We count how many zeros are in the original list using arr.count(0) to know how many zeros to add at the end.
Step 3: Combine lists
We add the zeros at the end of the non-zero list by concatenating the two lists, moving all zeros to the end.
Alternative Approaches
def move_zeros_in_place(arr): pos = 0 for i in range(len(arr)): if arr[i] != 0: arr[pos], arr[i] = arr[i], arr[pos] pos += 1 return arr arr = [0, 1, 0, 3, 12] print(move_zeros_in_place(arr))
def move_zeros_filter(arr): non_zero = list(filter(lambda x: x != 0, arr)) zeros = [0] * (len(arr) - len(non_zero)) return non_zero + zeros arr = [0, 1, 0, 3, 12] print(move_zeros_filter(arr))
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through the list once to filter non-zero elements and once to count zeros, both operations are O(n).
Space Complexity
It creates new lists for non-zero elements and zeros, so it uses O(n) extra space.
Which Approach is Fastest?
The in-place swapping method is fastest in space as it uses O(1) extra space, but the list comprehension method is simpler and more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| List comprehension + count | O(n) | O(n) | Readability and simplicity |
| In-place swapping | O(n) | O(1) | Memory efficiency and modifying original list |
| Filter + concatenation | O(n) | O(n) | Functional style and clarity |