Given an array of random numbers, Push all the zeros 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).
Examples:
Input : arr = [1, 2, 0, 4, 3, 0, 5, 0] Output : arr = [1, 2, 4, 3, 5, 0, 0, 0] Input : arr = [1, 2, 0, 0, 0, 3, 6] Output : arr = [1, 2, 3, 6, 0, 0, 0]
We have existing solution for this problem please refer Move all zeroes to end of array link. We will solve this problem in python using List Comprehension in a single line of code.
# Function to append all zeros at the end # of array def moveZeros(arr): # first expression returns a list of # all non zero elements in arr in the # same order they were inserted into arr # second expression returns a list of # zeros present in arr return [nonZero for nonZero in arr if nonZero!=0] + \ [Zero for Zero in arr if Zero==0] # Driver function if __name__ == "__main__": arr = [1, 2, 0, 4, 3, 0, 5, 0] print (moveZeros(arr)) |
Output:
[1, 2, 4, 3, 5, 0, 0, 0]
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Move all zeroes to end of array | Set-2 (Using single traversal)
- Move all zeroes to end of array using Two-Pointers
- Move all zeroes to end of array
- Python | Shift zeroes at end of list
- Python | Move element to end of the list
- Move all zeros to start and ones to end in an Array of random integers
- Move all values equal to K to the end of the Array
- Python List Comprehension | Segregate 0's and 1's in an array list
- Move all negative elements to end in order with extra space allowed
- Move all negative numbers to beginning and positive to end with constant extra space
- Python - Move Word to Rear end
- List comprehension and ord() in Python to remove all characters other than alphabets
- K’th Non-repeating Character in Python using List Comprehension and OrderedDict
- Count set bits using Python List comprehension
- Python | Move one list element to another list
- Python List Comprehension | Three way partitioning of an array around a given range
- Double the first element and move zero to end
- Check if a + b = c is valid after removing all zeroes from a, b and c
- Python List Comprehension and Slicing
- Python List Comprehension to find pair with given sum from two arrays

