Move Zeroes โ Python (In-Place Solution)
๐ Move Zeroes โ Python (In-Place Solution) Hi All, Today I solved a popular problem: Move all zeroes to the end of the array while maintaining the order of non-zero elements. ๐ Problem Statement ...

Source: DEV Community
๐ Move Zeroes โ Python (In-Place Solution) Hi All, Today I solved a popular problem: Move all zeroes to the end of the array while maintaining the order of non-zero elements. ๐ Problem Statement Given an array nums, move all 0s to the end while: Maintaining the relative order of non-zero elements Performing the operation in-place (no extra array) ๐ Examples Example 1: nums = [0, 1, 0, 3, 12] Output: [1, 3, 12, 0, 0] Example 2: nums = [0] Output: [0] ๐ก Approach ๐น Two Pointer Technique (Optimal) ๐ Idea: Use a pointer j to track position for non-zero elements Traverse array with i Swap non-zero elements forward ๐ง Step-by-Step Logic Initialize j = 0 Traverse array: If element is not zero: Swap nums[i] with nums[j] Increment j ๐ป Python Code def moveZeroes(nums): j = 0 for i in range(len(nums)): if nums[i] != 0: nums[i], nums[j] = nums[j], nums[i] j += 1 ๐ Dry Run For: nums = [0, 1, 0, 3, 12] Steps: Swap 1 โ [1, 0, 0, 3, 12] Swap 3 โ [1, 3, 0, 0, 12] Swap 12 โ [1, 3, 12, 0, 0] Final