
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 Given an array nums , move all 0 s 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,
Continue reading on Dev.to Python
Opens in a new tab



