In this task, I worked on rearranging an array so that all the zeroes are moved to the end, while keeping the order of the non-zero elements the same.
What I Did
I created a function called moveZeroes that takes an array and shifts all zero values to the end without changing the order of the other elements.
For example:
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
How I Solved It
To solve this problem, I used a variable called insert_pos to keep track of where the next non-zero element should go.
First, I went through the array:
If the element is not zero, I placed it at the insert_pos and moved the position forward
After placing all non-zero elements, I filled the remaining positions in the array with zeroes.
CODE:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
left = 0
for right in range(len(nums)):
if nums[right] != 0:
nums[right], nums[left] = nums[left], nums[right]
left += 1
return nums
Top comments (0)