One Pager Cheat Sheet
- Write a function
zerosToEnd
which moves all zeros in an array to its end, while maintaining the order of all other elements, withinO(n)
time andO(1)
space complexity constraints. - Run through examples and separate the
[1, 2, 4]
from the[0, 0, 0]
to achieve[1, 2, 4, 0, 0, 0]
. - We need to separate the
0
s and non-0
s, find out where the non-0
s need to be index-wise, and keep track of the number of0
s in order to solve this problem using a potential brute force solution. - We can do better by changing the position of elements in the array in-place, which requires us to mutate and keep track of indexes.
- Try simplifying the problem by only keeping track of one
index
, or usemultiple trackers
to know about multiple positions at once. - Multiple pointers are key for efficiently moving all
zeros
to the end of an array inO(n)
time complexity and constant space complexity.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
57
}
var assert = require('assert');
​
function zerosToEnd(nums) {
let insertPos = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[insertPos++] = nums[i];
}
}
​
for (let j = insertPos; j < nums.length; j++) {
nums[j] = 0;
}
​
return nums;
}
​
console.log(zerosToEnd([1, 0, 2, 0, 4, 0]));
​
try {
assert.deepEqual(zerosToEnd([1, 0, 2, 0, 4, 0]), [1, 2, 4, 0, 0, 0]);
​
console.log(
'PASSED: `zerosToEnd([1, 0, 2, 0, 4, 0])` should get us `[1, 2, 4, 0, 0, 0]`'
);
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(
zerosToEnd([4, 13, 0, 2, 0, 0, 15, 0]),
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.