After You Have A Working Solution
Here's a huge key that takes a while to click. After you've written pseudocode for an optimized solution, manually run through 1-3 example inputs, step by step, through your pseudocode to make sure it works. Warning: nerves will be there, and you may lose your place from time to time, but this is extremely important.
Good engineers test their code thoroughly and can step through logic. The space between having a pseudocode solution and writing code on the whiteboard is a good time to demonstrate this.
At this point, you'll also be able to weed out incorrect assumptions or make important realizations ("oh wait, we should use a Map
instead of a JS object instead").
Candidate: Let's start with
[1, 0, 3]
, I think that's a good test candidate. OK, starting with1
, we see that it's not a zero, so it can stay put. We're going to the next element so let's increment our final array index counter. Now we have0
, let's skip. OK,3
, not a zero, our counter is at1
so we put it after1
and we have[1, 3]
. Great! Then we put a0
at the end and we get the results we want.
The interviewer will likely say something like "great, let's code it up", or they may try to find out how confident you are in your solution. If the input-outputs check in, you should feel good about moving on.
Note: if you're going to be interviewing on a whiteboard, buy a Magnetic White Board Dry and practice handwriting code on it.
There's many things that people don't consider about coding on a whiteboard: space management mostly, but also how to use shorter variables, and writing horizontally.
Anyway, you've now written this code:
xxxxxxxxxx
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;
}