Move Zeroes - Complete Solution Guide
Move Zeroes is LeetCode problem 283, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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 that you must do this in-place without making a copy of the array. Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0] Constraints: 1 <= nums.length <= 10 4 -2 31 <= nums[i] <= 2 31 - 1 Follow up: Could you minimize the total number of operations done?
Detailed Explanation
The problem asks you to rearrange the elements of an integer array in place. The goal is to move all the zeros to the end of the array while preserving the relative order of the non-zero elements. For example, if the input array is `[0, 1, 0, 3, 12]`, the output should be `[1, 3, 12, 0, 0]`. The crucial constraint is that you cannot create a new array; you must modify the original array directly.
Solution Approach
The provided solutions use a two-pointer approach (in Python) or a single pointer approach (in Java, C++, and C). The single-pointer approach iterates through the array. When a non-zero element is encountered, it's placed at the beginning of a 'non-zero' subarray. This subarray expands as more non-zero numbers are found. Afterwards, the remaining elements are filled with zeros.
Step-by-Step Algorithm
- Step 1: Initialize a pointer (or counter) `k` to 0. This pointer will track the index of the next position to place a non-zero element.
- Step 2: Iterate through the input array `nums`. If an element `nums[i]` is not zero, copy it to `nums[k]` and increment `k`.
- Step 3: After the first loop, all non-zero elements are placed at the beginning of the array (from index 0 to `k-1`).
- Step 4: Iterate from `k` to the end of the array and set all elements to 0.
Key Insights
- Insight 1: We can use a two-pointer approach or a single pointer to efficiently track the position of the next non-zero element.
- Insight 2: The problem can be solved in-place without using extra space beyond a few constant variables.
- Insight 3: Optimizing the solution involves minimizing the number of array element swaps or assignments. Avoid unnecessary iterations.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Two Pointers.
Companies
Asked at: Agoda, Anduril, BNY Mellon, CEDCOSS, Capgemini, Cisco, Cognizant, CrowdStrike, DevRev, Infosys, Intuit, NetApp, Nvidia, Ozon, SAP, Salesforce, ServiceNow, Tesla, VK, Walmart Labs, Wix, Yandex, Zoho, eBay, josh technology, tcs.