Here is the interview question prompt, presented for reference.
Write a method that moves all zeros in an array to its end. You should maintain the order of all other elements. Here's an example:
zerosToEnd([1, 0, 2, 0, 4, 0])
// [1, 2, 4, 0, 0, 0]
Here's another one:
zerosToEnd([1, 0, 2, 0, 4, 0])
// [1, 2, 4, 0, 0, 0]
Fill in the following function signature:
function zerosToEnd(nums) {
return;
};
Can you do this without instantiating a new array?
100000
-1000000000
and 1000000000
O(n)
O(1)
You can see the full challenge with visuals at this link.
Challenges • Asked over 4 years ago by Anonymous
This is the main discussion thread generated for Zeros To The End.
The coding language choices are only javascript and python. It would be really nice if we could have C++ too.
[deleted]
C++ is coming soon, probably this spring 2021.
// Time - O(n), Space - O(1) :
public int[] zeroesToEnd(int[] A){
int n = A.length;
int pos = 0;
for (int i = 0; i < n; i++){
if (A[i] == 0){
pos++;
} else if (pos > 0){
A[i - pos] = A[i]
A[i] = 0;
}
}
return A;
}