Move Zeroes solution and explanation
9 more videos on this problem
Move Zeroes - Leetcode 283 - PythonNeetCode · 8:15 · 141K views
Move Zeroes (LeetCode 283) | Full Solution explained with examples | Study AlgorithmsNikhil Lohia · 10:43 · 61K views
How To Move Zeroes To End Of An Array ( LeetCode #283 ) | FREE DSA Course in JAVA | Lecture 67TAP ACADEMY · 12:56 · 46K views
Move Zeros | LeetCode problem 283Technosage · 3:53 · 25K views
[Java] Leetcode 283. Move Zeroes [Two Pointers #2]Eric Programming · 5:46 · 18K views
Leetcode 283. Move Zeroes [ Solution + Code Explained]jayati tiwari · 7:39 · 5K views
Move Zeroes - LeetCode 283 - Python #leetcode #leetcode75 #2pointersDeepti Talesra · 5:23 · 5K views
Leetcode | 283. Move Zeroes | Easy | Java SolutionDeveloper Docs · 4:21 · 5K views
LeetCode 283: Move Zeroes - Interview Prep Ep 53Fisher Coder · 13:00 · 5K views
Move Zeroes - LeetCode 283 - Two Pointers - Coding Interview QuestionsOne Code Man · 3:11 · 4K views
The problem
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 <= 104-231 <= nums[i] <= 231 - 1
Approach overview
Problem Overview: You are given an integer array nums. The task is to move all 0 values to the end of the array while keeping the relative order of non-zero elements unchanged. The operation must be done in-place without creating a new array.
Approach 1: Two-Pointer Approach (O(n) time, O(1) space)
This approach uses two indices to reorganize the array in a single pass. One pointer insertPos tracks where the next non-zero element should be written, while the other pointer scans the array from left to right. Each time you encounter a non-zero value, place it at insertPos and increment the pointer. After the scan completes, fill the remaining positions with zeroes. The key insight is separating the discovery of non-zero values from their final placement, which preserves order naturally. This technique is a classic application of the two pointers pattern on an array. Time complexity is O(n) because each element is visited once, and space complexity is O(1) since all operations happen in-place.
Approach 2: Swap with Two-Pointer Technique (O(n) time, O(1) space)
This variation keeps two pointers: left for the position where the next non-zero element should go, and right for scanning the array. When nums[right] is non-zero, swap it with nums[left], then move both pointers forward. If the current element is zero, only advance right. The swap guarantees that non-zero values gradually shift toward the front while zeroes drift toward the end. Because each element participates in at most one swap, the algorithm still runs in O(n) time with O(1) extra space. This method is often preferred when you want a direct in-place transformation without a second pass to fill zeroes.
Recommended for interviews: Interviewers typically expect the linear O(n) in-place solution using the two-pointer technique. A brute-force approach that repeatedly shifts elements would degrade to O(n^2), which signals inefficient array manipulation. Demonstrating the optimal pointer-based strategy shows you understand how to process arrays with minimal movement and constant space, a common pattern in interview problems.
Approach 1: Two-Pointer Approach
This approach uses two pointers: one to track the position for the next non-zero element and the other to iterate through the array. We move all non-zero elements to the beginning of the array using these two pointers and fill the remaining positions with zeroes.
def moveZeroes(nums):
lastNonZeroFoundAt = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[lastNonZeroFoundAt] = nums[i]
lastNonZeroFoundAt += 1
for i in range(lastNonZeroFoundAt, len(nums)):
nums[i] = 0public class Solution {
public void moveZeroes(int[] nums) {
int lastNonZeroFoundAt = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
for (int i = lastNonZeroFoundAt; i < nums.length; i++) {
nums[i] = 0;
}
}
}#include <vector>
using namespace std;
void moveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
nums[i] = 0;
}
}var moveZeroes = function(nums) {
let lastNonZeroFoundAt = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
for (let i = lastNonZeroFoundAt; i < nums.length; i++) {
nums[i] = 0;
}
};#include <stdio.h>
void moveZeroes(int* nums, int numsSize) {
int lastNonZeroFoundAt = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
for (int i = lastNonZeroFoundAt; i < numsSize; i++) {
nums[i] = 0;
}
}public class Solution {
public void MoveZeroes(int[] nums) {
int lastNonZeroFoundAt = 0;
for (int i = 0; i < nums.Length; i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
for (int i = lastNonZeroFoundAt; i < nums.Length; i++) {
nums[i] = 0;
}
}
}In Python, we iteratively move non-zero elements to the front using lastNonZeroFoundAt as a pointer and then fill the rest of the array with zeroes.
Time Complexity: O(n), making a single pass through the list.
Space Complexity: O(1), since replacements are made in the original list.
Approach 2: Swap with Two-Pointer Technique
This method uses a two-pointer technique where we place one pointer at the beginning of the array and the other to iterate through the array. Whenever we encounter a non-zero element, we swap it with the first pointer's position, allowing us to effectively move zeroes to the end by swapping.
def moveZeroes(nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1public class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
j++;
}
}
}
}#include <vector>
using namespace std;
void moveZeroes(vector<int>& nums) {
int j = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
swap(nums[j++], nums[i]);
}
}
}var moveZeroes = function(nums) {
let j = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
[nums[j], nums[i]] = [nums[i], nums[j]];
j++;
}
}
};#include <stdio.h>
void moveZeroes(int* nums, int numsSize) {
int j = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] != 0) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
j++;
}
}
}public class Solution {
public void MoveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.Length; i++) {
if (nums[i] != 0) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
j++;
}
}
}
}The Python version leverages tuple unpacking to swap elements at positions j and i. The j pointer ensures that swaps occur only with zeros, keeping all non-zero elements ordered.
Time Complexity: O(n), with each element checked directly.
Space Complexity: O(1), in-place swaps with no extra memory utilization.
Approach 3: Two Pointers
We use a pointer k to record the current position to insert, initially k = 0.
Then we iterate through the array nums, and each time we encounter a non-zero number, we swap it with nums[k] and increment k by 1.
This way, we can ensure that the first k elements of nums are non-zero, and their relative order is the same as in the original array.
The time complexity is O(n), where n is the length of the array nums. The space complexity is O(1).
/**
Do not return anything, modify nums in-place instead.
*/
function moveZeroes(nums: number[]): void {
let k = 0;
for (let i = 0; i < nums.length; ++i) {
if (nums[i]) {
[nums[i], nums[k]] = [nums[k], nums[i]];
++k;
}
}
}func moveZeroes(nums []int) {
k := 0
for i, x := range nums {
if x != 0 {
nums[i], nums[k] = nums[k], nums[i]
k++
}
}
}impl Solution {
pub fn move_zeroes(nums: &mut Vec<i32>) {
let mut k = 0;
let n = nums.len();
for i in 0..n {
if nums[i] != 0 {
nums.swap(i, k);
k += 1;
}
}
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Two-Pointer Approach | Time Complexity: O(n), making a single pass through the list. |
| Swap with Two-Pointer Technique | Time Complexity: O(n), with each element checked directly. |
| Two Pointers | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Two-Pointer (Overwrite Non-Zero Elements) | O(n) | O(1) | General case when you want stable ordering and minimal swaps |
| Swap with Two-Pointer Technique | O(n) | O(1) | When an in-place transformation using swaps is simpler to implement |
Frequently asked questions
Is Move Zeroes easy or hard?
Move Zeroes is categorized as an Easy problem on LeetCode with an acceptance rate above 60%. Despite the difficulty label, it reinforces an essential interview pattern: in-place array manipulation using two pointers.
Move Zeroes Python/Java solution
In both Python and Java, the standard solution uses two pointers. Iterate through the array, move each non-zero value to the next available position, and optionally swap elements when needed. This produces an O(n) time and O(1) space implementation.
How to solve Move Zeroes in O(n)?
Maintain two pointers: one scanning the array and another tracking the position of the next non-zero element. When a non-zero value appears, move or swap it to the tracked position. This single-pass strategy processes all elements once and keeps zeroes pushed toward the end.
What is the best approach for Move Zeroes?
The optimal solution uses the two-pointer technique with O(n) time and O(1) extra space. One pointer scans the array while another tracks the position for the next non-zero element. This preserves the relative order of non-zero values and performs the transformation in-place.
Is Move Zeroes asked at Google/Amazon/Meta?
Move Zeroes is a common array manipulation problem that appears in coding interviews at companies like Amazon, Meta, and Google. It tests understanding of in-place array operations and the two-pointer pattern, both frequently used in real interview questions.
What data structure is used in Move Zeroes?
The problem operates directly on an array. The key algorithmic technique is the two-pointer method, which allows efficient in-place modification while maintaining the relative order of elements.
What is the time complexity of Move Zeroes?
The optimal approach runs in O(n) time because the array is scanned only once. Each element is processed exactly once, and swaps or writes happen at most n times. Space complexity remains O(1) since no additional data structures are required.
