Back to articles
Move Zeores

Move Zeores

via Dev.to BeginnersSruthika Ramachandran

**Introduction ** In array manipulation problems, we often need to rearrange elements while maintaining their order. This problem focuses on moving all 0 s to the end of the array while keeping the relative order of non-zero elements unchanged . Problem Statement Given an integer array nums , move all 0 s to the end while maintaining the order of non-zero elements. Constraints: Perform the operation in-place Do not create a copy of the array Examples Example 1: Input: [0, 1, 0, 3, 12] Output: [1, 3, 12, 0, 0] Example 2: Input: [0] Output: [0] Intuition Move all non-zero elements forward Fill remaining positions with 0 s This ensures: Order is maintained No extra space is used Approach We use a pointer j to track the position where the next non-zero element should go. Algorithm Steps Initialize j = 0 Traverse array using i : If nums[i] != 0 : Swap nums[i] with nums[j] Increment j End result: all non-zero elements are shifted forward, zeros move to end Code (Python) def move_zeroes ( num

Continue reading on Dev.to Beginners

Opens in a new tab

Read Full Article
5 views

Related Articles