
Move Zeros
Introduction Moving zeros in an array is a common problem that helps in understanding array manipulation and two-pointer techniques. Problem Statement Given an array, move all zeros to the end while maintaining the relative order of non-zero elements. Approach (Two-Pointer Technique) We use two pointers: Initialize a pointer j = 0 (position for non-zero elements) Traverse the array using index i If element is non-zero: Swap arr[i] with arr[j] Increment j Continue until the end Python Code python def move_zeros(arr): j = 0 for i in range(len(arr)): if arr[i] != 0: arr[i], arr[j] = arr[j], arr[i] j += 1 return arr # Example arr = [0, 1, 0, 3, 12] print("Result:", move_zeros(arr)) ## Input [0,1,0,3,4] ## Output [1,3,4,0,0]
Continue reading on Dev.to Python
Opens in a new tab


