Skip to main content

Move Zeroes

LeetCode 283 | Difficulty: Easy​

Easy

Problem Description​

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?

Topics: Array, Two Pointers


Approach​

Two Pointers​

Use two pointers to traverse the array, reducing the search space at each step. This avoids the need for nested loops, bringing complexity from O(nΒ²) to O(n) or O(n log n) if sorting is involved.

When to use

Array is sorted or can be sorted, and you need to find pairs/triplets that satisfy a condition.


Solutions​

Solution 1: C# (Best: 236 ms)​

MetricValue
Runtime236 ms
Memory31.8 MB
Date2020-04-06
Solution
public class Solution {
public void MoveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.Length; i++)
{
if(nums[i]!=0)
{
if(index!=i){
int temp = nums[index];
nums[index] = nums[i];
nums[i] = temp;
}
index++;
}

}
}
}
πŸ“œ 2 more C# submission(s)

Submission (2018-05-11) β€” 292 ms, N/A​

public class Solution {
public void MoveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.Length; i++)
{
if(nums[i]!=0)
{
if(index!=i){
int temp = nums[index];
nums[index] = nums[i];
nums[i] = temp;
}
index++;
}

}
}
}

Submission (2018-05-11) β€” 292 ms, N/A​

public class Solution {
public void MoveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.Length; i++)
{
if(nums[i]!=0)
{
int temp = nums[index];
nums[index] = nums[i];
nums[i] = temp;
index++;
}

}
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Ask: "Can I sort the array?" β€” Sorting often enables two-pointer techniques.
  • LeetCode provides 2 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually.

Hint 2: A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.