Shift All Zeros to the End of the Array

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given an array nums, return the array with every zero moved to the end, while every non-zero value keeps its original relative order. Try to do it by rearranging values in a single pass rather than building a second array — a two-pointer swap gets you there in O(1) extra space.

Test Case 1:

Input:nums = [0, 5, 0, 3, 9, 0]
Output:[5, 3, 9, 0, 0, 0]
Explanation:The non-zero values keep their original order; the zeros all land at the end.

Test Case 2:

Input:nums = [4, 2, 7]
Output:[4, 2, 7]
Explanation:No zeros to move, so nothing changes.

Test Case 3:

Input:nums = [0, 0, 0]
Output:[0, 0, 0]
Explanation:All zeros — moving them to the end leaves the array as it was.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public int[] moveZeroesToEnd(int[] nums) {
3 int[] result = nums.clone();
4 int insertPos = 0;
5 for (int i = 0; i < result.length; i++) {
6 if (result[i] != 0) {
7 int tmp = result[insertPos];
8 result[insertPos] = result[i];
9 result[i] = tmp;
10 insertPos++;
11 }
12 }
13 return result;
14 }
15}
16
0
5
0
3
9
0
0
1
2
3
4
5
insertPos
Variables
insertPos0
INITIALIZE

Copy nums into result, and set insertPos to 0 — that's where the next non-zero value will land.

Step 1 / 8

Approach & Solutions

Brute Force — Two Separate Arrays

Brute

Make one pass to collect every non-zero value into a fresh array, then append as many zeros as were left out. Easy to follow, but it needs a second array the same size as the input just to hold the answer, when the values could be rearranged directly.

TimeO(n)
SpaceO(n)
1class Solution { 2 public int[] moveZeroesToEnd(int[] nums) { 3 int[] result = new int[nums.length]; 4 int idx = 0; 5 for (int num : nums) { 6 if (num != 0) result[idx++] = num; 7 } 8 while (idx < nums.length) result[idx++] = 0; 9 return result; 10 } 11}

Optimal — Two-Pointer Swap

Optimal

Keep a pointer, insertPos, marking where the next non-zero value belongs. Scan the array once — whenever you find a non-zero value, swap it into position insertPos and advance that pointer. Every zero naturally gets pushed later in the array as swaps happen around it, with no second array needed.

TimeO(n)
SpaceO(1) extra
1class Solution { 2 public int[] moveZeroesToEnd(int[] nums) { 3 int[] result = nums.clone(); 4 int insertPos = 0; 5 for (int i = 0; i < result.length; i++) { 6 if (result[i] != 0) { 7 int tmp = result[insertPos]; 8 result[insertPos] = result[i]; 9 result[i] = tmp; 10 insertPos++; 11 } 12 } 13 return result; 14 } 15}

Related Problems