Python3 Program to Move all zeroes to end of array
Last Updated :
06 Sep, 2024
Given an array of random numbers, Push all the zero's of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).
Example:
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output : arr[] = {1, 2, 4, 3, 5, 0, 0};
Input : arr[] = {1, 2, 0, 0, 0, 3, 6};
Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
There can be many ways to solve this problem. Following is a simple and interesting way to solve this problem.
Traverse the given array 'arr' from left to right. While traversing, maintain count of non-zero elements in array. Let the count be 'count'. For every non-zero element arr[i], put the element at 'arr[count]' and increment 'count'. After complete traversal, all non-zero elements have already been shifted to front end and 'count' is set as index of first 0. Now all we need to do is that run a loop which makes all elements zero from 'count' till end of the array.
Below is the implementation of the above approach.
Python3
# Python3 code to move all zeroes
# at the end of array
# Function which pushes all
# zeros to end of an array.
def pushZerosToEnd(arr, n):
count = 0 # Count of non-zero elements
# Traverse the array. If element
# encountered is non-zero, then
# replace the element at index
# 'count' with this element
for i in range(n):
if arr[i] != 0:
# here count is incremented
arr[count] = arr[i]
count+=1
# Now all non-zero elements have been
# shifted to front and 'count' is set
# as index of first 0. Make all
# elements 0 from count to end.
while count < n:
arr[count] = 0
count += 1
# Driver code
arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]
n = len(arr)
pushZerosToEnd(arr, n)
print("Array after pushing all zeros to end of array:")
print(arr)
# This code is contributed by "Abhishek Sharma 44"
OutputArray after pushing all zeros to end of array:
[1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0]
Time Complexity: O(n) where n is number of elements in input array.
Auxiliary Space: O(1)
Method 2: Using two pointer
- Initialize a pointer variable 'left' to 0 and another pointer variable 'right' to n-1, where n is the length of the array.
- Repeat the following steps until the value of 'left' is less than or equal to 'right':
a. If the value at index 'left' is non-zero, increment the value of 'left'.
b. If the value at index 'right' is zero, decrement the value of 'right'.
c. If the value at index 'left' is zero and the value at index 'right' is non-zero, swap the values at these indices and then increment the value of 'left' and decrement the value of 'right'. - The above steps will move all the zeros to the end of the array and all the non-zero values to the front of the array.
Python
def pushZerosToEnd(arr, n):
# Initialize two pointers - 'left' and 'right' - pointing to the first and last elements of the array respectively
left = 0
right = n - 1
# Loop until 'left' pointer crosses 'right' pointer
while left <= right:
# If the element at the 'left' pointer is non-zero, increment 'left'
if arr[left] != 0:
left += 1
# If the element at the 'right' pointer is zero, decrement 'right'
elif arr[right] == 0:
right -= 1
# If the element at the 'left' pointer is zero and the element at the 'right' pointer is non-zero, swap the two elements and increment 'left' and decrement 'right'
else:
# Move all non-zero elements to the left of the array
for i in range(left, right):
if arr[i] == 0:
arr[i], arr[i+1] = arr[i+1], arr[i]
# Decrement the 'right' pointer after each swap
right -= 1
# Driver code
arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]
n = len(arr)
pushZerosToEnd(arr, n)
print("Array after pushing all zeros to end of array:")
print(arr)
OutputArray after pushing all zeros to end of array:
[1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0]
Time complexity: The time complexity of this approach is O(n), where n is the length of the array.
Auxiliary space: The space complexity of this approach is O(1), as it only uses two pointers and a few variables for swapping.
Please refer complete article on Move all zeroes to end of array for more details!
Similar Reads
Python3 Program to Move all zeroes to end of array | Set-2 (Using single traversal)
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples: Input : arr[] = {1, 2, 0, 0, 0, 3, 6}Output : 1 2 3 6 0 0 0Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0,
2 min read
Python Program to Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..... Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR
3 min read
How to create an array of zeros in Python?
Our task is to create an array of zeros in Python. This can be achieved using various methods, such as numpy.zeros(), which is efficient for handling large datasets. Other different methods are:Using the In-Build method numpy.zeros() methodUsing simple multiplication Using List comprehensionUsing it
5 min read
Python program to create a list centered on zero
Given two integer variables, limit and diff, write a Python program to create a list that is centered on zero, using limit, which specifies limit of the list and diff that specifies the common difference between integers. Examples: Input : limit = 1, diff = 0.5 Output : [-1, -0.5, 0.0, 0.5, 1] Input
3 min read
Python Program to move numbers to the end of the string
Given a string, the task is to write a Python program to move all the numbers in it to its end. Examples: Input : test_str = 'geek2eeks4g1eek5sbest6forall9' Output : geekeeksgeeksbestforall241569 Explanation : All numbers are moved to end. Input : test_str = 'geekeeksg1eek5sbest6forall9' Output : ge
6 min read
Python Program for Remove leading zeros from a Number given as a string
Given numeric string str, the task is to remove all the leading zeros from a given string. If the string contains only zeros, then print a single "0".Examples:Input: str = "0001234" Output: 1234 Explanation: Removal of leading substring "000" modifies the string to "1234". Hence, the final answer is
3 min read
Python3 Program for Reversal algorithm for right rotation of an array
Given an array, right rotate it by k elements.  After K=3 rotation  Examples:  Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3Output: 8 9 10 1 2 3 4 5 6 7Input: arr[] = {121, 232, 33, 43 ,5} k = 2Output: 43 5 121 232 33Note : In the below solution, k is assumed to be smaller than or equal to n.
2 min read
Python | Shift zeroes at end of list
The conventional problem involving the element shifts has been discussed many times earlier, but sometimes we have strict constraints performing them and knowledge of any possible variation helps. This article talks about one such problem of shifting 0's at end of list, catch here is it checks for j
7 min read
Python Program to Split a List into Two Halves
Splitting a list into two halves is a common operation that can be useful in many cases, such as when dealing with large datasets or when performing specific algorithms (e.g., merge sort). In this article, we will discuss some of the most common methods for splitting a list into two halves.Using Lis
4 min read
Python3 Program for Segregate 0s and 1s in an array
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once. Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] Method 1 (Count 0s or 1s) Thanks to Naveen for suggesting this method
3 min read