Move zeroes in matrix

This question was asked in Microsoft’s frontend interview. Enroll into alpha.learnersbucket.com to practice frontend interview questions company-wise.

Move zeroes in Matrix is an advanced version of Move zeroes in Array problem where given an array of integers move all the zeroes to the end of the array by maintaining the relative order of the non-zeroes elements.

Example

Input:
const matrix = [
  [0,1,0,3,12],
  [0,1,0,0,12],
  [1,1,0,3,12]
];

Output:
[
[1,3,12,0,0],
[1,12,0,0,0],
[1,1,3,12,0]
]

We can solve this by implementing the logic to move all the zeroes to the end of the array and then reusing that logic for each row of the matrix.

To move the zeroes to the end in-place, we can use the two pointer method. Where we can iterate the array and then maintain an extra pointer that brings all the non-zero elements at the beginning in their relative order leaving all the zeroes at the end.

const moveZeroes = (arr) => {
    let pointer = 0;

    for (let i = 0; i < arr.length; i++) {
        // if a non-zero element is encountered
        if (arr[i] !== 0) {
            // only swap distinctive elements 
            if (i !== pointer) {
                // swap the elements and bring them to the front of the array
                [arr[pointer], arr[i]] = [arr[i], arr[pointer]];
            }
            
            // shift the pointer to the next index
            pointer++;
        }
    } 
};

Testcase

Input:
console.log(moveZeroes([0,1,0,0,12]));

Output:
[1,12,0,0,0]

We can use this function on each row of the matrix to move zeroes to the end.

const matrix = [
  [0,1,0,3,12],
  [0,1,0,0,12],
  [1,1,0,3,12]
];

const moveZeroMatrics = (matrix) => {
  matrix.forEach((row) => {
    moveZeroes(row);
  });
}

moveZeroMatrics(matrix);

console.log(matrix);
/*
[
[1,3,12,0,0],
[1,12,0,0,0],
[1,1,3,12,0]
]
*/