Search a 2D Matrix in TypeScript

function searchMatrix(matrix: number[][], target: number): boolean {
    // Get the number of rows (m) and columns (n) in the matrix
    const m = matrix.length;
    const n = matrix[0].length;
    
    // Initialize two pointers: left and right
    let left = 0;
    let right = m * n - 1;
    
    // Perform binary search on the flattened matrix
    while (left <= right) {
        // Calculate the middle index
        const mid = Math.floor((left + right) / 2);
        
        // Convert the middle index to row and column indices
        const row = Math.floor(mid / n);
        const col = mid % n;
        
        // Get the middle element
        const midElement = matrix[row][col];
        
        // If the middle element is equal to the target, return true
        if (midElement === target) {
            return true;
        }
        
        // If the middle element is greater than the target,
        // search the left half of the matrix
        if (midElement > target) {
            right = mid - 1;
        }
        // If the middle element is less than the target,
        // search the right half of the matrix
        else {
            left = mid + 1;
        }
    }
    
    // If the target is not found, return false
    return false;
}

PrevNext