
NewsWeb Development
Move Zeros
via Dev.toLuckshvadhan B
Approach: Step 1 Take the array Step 2 Keep a pointer pos = 0 Step 3 Traverse array Step 4 If element not zero place it at pos and move pos Step 5 Fill remaining positions with 0 Why this works??? Non zero elements move forward in same order zeros automatically shift to end no extra space used Code: def moveZeroes(nums): pos = 0 for i in range(len(nums)): if nums[i]!=0: nums[pos]=nums[i] pos+=1 for i in range(pos, len(nums)): nums[i]=0 Limitation: Overwrites array values but works in place
Continue reading on Dev.to
Opens in a new tab
6 views

