Moving zeroes is one of the popular questions in coding interviews. Here we need to move all the 0’s in an array to the end of the array while keeping the order of non-zero elements the same. So, if you want to know how to solve this problem using Python, this article is for you. This article will take you through how to move zeroes using Python.
Move Zeroes using Python
In the problem of moving zeroes, you will be given an array of zero and non-zero elements in random order. To solve the problem of moving zeroes, you need to move all the zeroes present in the array at the end of the array. Besides moving the zeroes, you don’t need to change the order of other non-zero elements. Below is an example of the input and output of this problem:
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
I hope you have understood what the problem of moving zeroes means. Now, below is how you can solve this problem using the Python programming language:
def moveZeroes(nums): zeroes = 0 for i in range(len(nums)): if nums[i] > 0: nums[zeroes], nums[i] = nums[i], nums[zeroes] zeroes = zeroes + 1 return nums nums = [0, 1, 0, 3, 12] print(moveZeroes(nums))
Output: [1, 3, 12, 0, 0]
So this is how you can move zeroes in an array to the end of the array using Python. You can find many more practice questions for coding interviews solved and explained using Python here.
Summary
In the problem of moving zeroes, you will be given an array of zero and non-zero elements in random order. To solve the problem of moving zeroes, you need to move all the zeroes present in the array at the end of the array. I hope you liked this article on how to move zeroes using Python. Feel free to ask valuable questions in the comments section below.