OVERVIEW
In this task, I worked on moving all the zeroes in an array to the end while maintaining the order of non-zero elements.
WHAT I DID
I created a function that rearranges the array such that:
- All non-zero elements stay in the front
- All zeroes move to the end
- The relative order remains the same
EXAMPLE
Input : nums = [0, 1, 0, 3, 12]
output : [1, 3, 12, 0, 0]
LOGIC IMPLEMENTED
To solve this problem, I used a two-pointer approach:
- One pointer (pos) keeps track of where to place the next non-zero element
- The other pointer (i) traverses the array
- Traverse the array
- If element is non-zero:
- Swap it with position pos
- Move pos forward
HOW IT WORKS
- First, all non-zero elements are shifted to the front
- While doing that, zeroes automatically move to the end
- The order of non-zero elements is preserved
class Solution:
def moveZeroes(self, nums):
pos = 0 # position for next non-zero element
for i in range(len(nums)):
if nums[i] != 0:
nums[pos], nums[i] = nums[i], nums[pos]
pos += 1
Top comments (0)