Problem Statement
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note: You must do this in-place without making a copy of the array.
Examples:
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Input: nums = [0]
Output: [0]
Solution:
For this problem, my goal was to maintain the order of non-zero elements while moving all zeros to the end efficiently. I also wanted to solve it in-place without using any extra array, keeping the approach simple and optimal.
For the solution, I used a two-pointer approach. One pointer is used to track where the next non-zero element should be placed, and the other pointer is used to traverse the array. Whenever I find a non-zero element, I swap it with the position tracked by the first pointer and move that pointer forward. This way, all non-zero elements are shifted to the front in order, and zeros automatically end up at the back.
Solution Code (Python)
a = [0, 1, 0, 3, 12]
i = 0
for j in range(len(a)):
if a[j] != 0:
a[i], a[j] = a[j], a[i]
i += 1
print(a)
Top comments (0)