educative.io

Educative

Solution without tracking indices

Hi,

On the ‘move all zeros’ problem, instead of tracking indices, I think the count of zeros found starting from the back of the array can be used to determine where each value should be moved. Then, from the front of the array, write a 0 based on how many zeros were found. I’ve tested on multiple sets, please let me know if there’s any issue with this approach.

Thanks!

const moveZerosToLeft = function(arr) {
    let zeroCount = 0;

    let i = arr.length - 1;
    while (i >= 0) {
        if (arr[i] === 0) {
            zeroCount += 1;
        } else {
            arr[i + zeroCount] = arr[i];
        }
        
        i -= 1;
    }

    if (zeroCount && zeroCount < arr.length) {
        for (let i = 0; i < zeroCount; i+=1) {
            arr[i] = 0;
        }
    }

    return arr;
};

Hi @Shawn2. I have tested your code on plenty of inputs that also include many corner cases but neither of those test cases got failed. You have written brilliant logic and your code is working perfectly fine. Great job. Happy Learning :smiley:

Thank you!

1 Like