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_posand moved the position forward
After placing all non-zero elements, I filled the remaining positions in the array with zeroes.
Code
def moveZeroes(nums):
insert_pos = 0
for num in nums:
if num != 0:
nums[insert_pos] = num
insert_pos += 1
while insert_pos < len(nums):
nums[insert_pos] = 0
insert_pos += 1
nums = [0, 1, 0, 3, 12]
print("Before:", nums)
moveZeroes(nums)
print("After:", nums)
How It Works
The function first shifts all non-zero elements to the front of the array while keeping their order unchanged. Then it fills the remaining positions with zeroes.
This way, the operation is done in a single pass without using extra space, making it efficient and easy to understand.
Top comments (0)