Coding Challenge – Bring all nonzero elements to the left of the array

Question:

Write an algorithm that brings all nonzero elements to the left of the array, and returns the number of nonzero elements.

Input : {1, 2, 0, 4, 3, 0, 5, 0}; 
Output : {1, 2, 4, 3, 5, 0, 0};
 
Input : {1, 2, 0, 0, 0, 3, 6}; 
Output : {1, 2, 3, 6, 0, 0, 0};

Solution:

To solve this problem first we can use for loop to check the value of the array element.

If the value is non-zero we do nothing, otherwise we will use temporary variable to swap the zero value with non-zero value.

const zeroTransfer = (arr) => {
    let j = arr.length - 1;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 0) {
            while (arr[j] === 0 && j > i) {
                j--;
            }
            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

    return arr;
}

Here is the another algorithm which uses count as index of the array:


const countZeros = (arr) => {

    let count = 0;
    for (let i = 0; i < arr.length; i++) {

        if (arr[i] !== 0) {
            arr[count++] = arr[i];
        }

    }
    while (count < arr.length) {
        arr[count++] = 0;
    }

    return arr;
}
Test Case Function:

const testCase = (expected, actual) => {

  return `Expected: ${expected} Actual: ${actual}`;

}

console.log(testCase([1, 2, 4, 3, 5, 0, 0], countZeros([1, 2, 0, 4, 3, 0, 5, 0]));

console.log(testCase([1, 2, 0, 0, 0, 3, 6], countZeros([1, 2, 0, 0, 0, 3, 6]));