Skip to content
thesarfo

Reference

Move Zeros to the End

Preserving non-zero order while pushing all zeros to the end, using a temp array vs. two pointers in place.

views 0

[1,0,2,3,2,0,0,4,5,1][1,2,3,2,4,5,1,0,0,0], preserving the order of non-zero elements. (LeetCode 283)

Brute force: collect non-zero elements into a temp array, copy them back, then fill the rest with zeros. O(n) time, O(n) space.

Optimal — two pointers, in-place: j tracks the position of the first zero; i scans forward from j+1, and whenever a non-zero is found, swap it into position j and advance j.

j = -1;
for(int i = 0; i < n; i++){
if(arr[i] == 0){
j = i;
break;
}
}
for(int i = j + 1; i < n; i++){
if(arr[i] != 0){
swap(arr[i], arr[j]);
j++;
}
}

Time: O(n). Space: O(1).