Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Move Zeroes in Python
Sometimes we need to move all zero values in an array to the right while maintaining the relative order of non-zero elements. For example, transforming [0, 1, 5, 0, 3, 8, 0, 0, 9] into [1, 5, 3, 8, 9, 0, 0, 0, 0].
Algorithm Approach
We use a two-pointer technique to solve this problem efficiently ?
- Use an
insert_indexpointer to track where to place the next non-zero element - Iterate through the array and move non-zero elements to the front
- Fill remaining positions with zeros
Using Two-Pointer Method
This approach modifies the array in-place with O(n) time complexity ?
def move_zeroes(nums):
"""
Move all zeros to the right while maintaining relative order of non-zeros
"""
insert_index = 0
# First pass: move all non-zero elements to the front
for i in range(len(nums)):
if nums[i] != 0:
nums[insert_index] = nums[i]
insert_index += 1
# Second pass: fill remaining positions with zeros
for i in range(insert_index, len(nums)):
nums[i] = 0
# Example usage
numbers = [0, 1, 5, 0, 3, 8, 0, 0, 9]
print("Original array:", numbers)
move_zeroes(numbers)
print("After moving zeros:", numbers)
Original array: [0, 1, 5, 0, 3, 8, 0, 0, 9] After moving zeros: [1, 5, 3, 8, 9, 0, 0, 0, 0]
Class-Based Implementation
Here's the same logic implemented as a class method ?
class Solution:
def moveZeroes(self, nums):
"""
Modifies nums in-place to move all zeros to the right
"""
insert_index = 0
# Move non-zero elements to the front
for i in range(len(nums)):
if nums[i] != 0:
nums[insert_index] = nums[i]
insert_index += 1
# Fill remaining positions with zeros
for i in range(insert_index, len(nums)):
nums[i] = 0
# Test the solution
solution = Solution()
test_array = [0, 1, 5, 0, 3, 8, 0, 0, 9]
print("Before:", test_array)
solution.moveZeroes(test_array)
print("After:", test_array)
Before: [0, 1, 5, 0, 3, 8, 0, 0, 9] After: [1, 5, 3, 8, 9, 0, 0, 0, 0]
How It Works
The algorithm works in two phases:
-
Phase 1: Copy all non-zero elements to the beginning of the array using
insert_index -
Phase 2: Fill all remaining positions from
insert_indexto the end with zeros
Key Points
- Time Complexity: O(n) - we traverse the array twice
- Space Complexity: O(1) - in-place modification
- Stability: Maintains relative order of non-zero elements
- In-place: No additional array needed
Conclusion
The two-pointer approach efficiently moves all zeros to the right while preserving the order of non-zero elements. This solution is optimal with O(n) time complexity and constant space usage.
Advertisements
