Queries to count sum of rows and columns of a Matrix present in given ranges | Function to preprocess the matrix to execute the queries ; Stores the sum of each row ; Stores the sum of each col ; Traverse the matrix and calculate sum of each row and column ; Insert all row sums in sum_list ; Insert all column sums in sum_list ; Sort the array in ascending order ; Traverse the array queries [ ] [ ] ; Search the leftmost index of L ; Search the rightmost index of R ; Function to search for the leftmost index of given number ; Initialize low , high and ans ; Stores mid ; If A [ mid ] >= num ; Function to search for the rightmost index of given number ; Initialise low , high and ans ; Stores mid ; If A [ mid ] <= num ; Update ans ; Update mid ; Update high ; Given dimensions of matrix ; Given matrix ; Given number of queries ; Given queries ; Function call to count the number row - sums and column - sums present in the given ranges
function totalCount ( A , N , M , queries , Q ) { let row_sum = new Array ( N ) ; let col_sum = new Array ( M ) ; for ( let i = 0 ; i < N ; i ++ ) row_sum [ i ] = 0 ; for ( let j = 0 ; j < M ; j ++ ) col_sum [ j ] = 0 ; for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < M ; j ++ ) { row_sum [ i ] += A [ i ] [ j ] ; col_sum [ j ] += A [ i ] [ j ] ; } } let sum_list = [ ] ; for ( let i = 0 ; i < N ; i ++ ) sum_list . push ( row_sum [ i ] ) ; for ( let i = 0 ; i < M ; i ++ ) sum_list . push ( col_sum [ i ] ) ; ( sum_list ) . sort ( function ( a , b ) { return a - b ; } ) ; for ( let i = 0 ; i < Q ; i ++ ) { let L = queries [ i ] [ 0 ] ; let R = queries [ i ] [ 1 ] ; let l = left_search ( sum_list , L ) ; let r = right_search ( sum_list , R ) ; document . write ( r - l + 1 + " " ) ; } } function left_search ( A , num ) { let low = 0 , high = A . length - 1 ; let ans = 0 ; while ( low <= high ) { let mid = low + Math . floor ( ( high - low ) / 2 ) ; if ( A [ mid ] >= num ) { ans = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } return ans ; } function right_search ( A , num ) { let low = 0 , high = A . length - 1 ; let ans = high ; while ( low <= high ) { let mid = low + Math . floor ( ( high - low ) / 2 ) ; if ( A [ mid ] <= num ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } let N = 3 , M = 2 ; let A = [ [ 13 , 3 ] , [ 9 , 4 ] , [ 6 , 10 ] ] ; let Q = 2 ; let queries = [ [ 10 , 20 ] , [ 25 , 35 ] ] ; totalCount ( A , N , M , queries , Q ) ;