# Count of numbers in given range L to R which are present in a Matrix

Given a matrix(mat[][]), which is sorted row and column-wise in increasing order. Two integers are given, L and R, our task is to count number of elements of the matrix within the range [L, R].

Examples:

Input: L = 3, R = 11, matrix =
{{1, 6, 9}
{2, 7, 11}
{3, 8, 12}}
Output: 6
Explanation:
The elements which are in this range [3, 11] are 3, 6, 7, 8, 9, 11.

Input: L = 20, R = 26, matrix =
{{1, 6, 19}
{2, 7, 31}
{3, 8, 42}}
Output: 0
Explanation:
No element is in this range.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: To solve the problem mentioned above the naive method would be to do a row-wise traversal through the matrix.

For each row, we check each element of that row and if it is in the given range, then we increment count. Finally, we return the count.

Time complexity: O(M * N), where M is the number of rows and N is the number of columns.

Efficient Approach: To optimize the above-mentioned approach:

1. First we count the elements which are less than L. Lets consider it as count1. We start traversing from the last element of the first column and this includes the following two steps:
• If the current iterating element is less than L, we increment count1 by corresponding row + 1 as elements in that column above current element (including current element) must be less than L. We increment column index.
• If the current iterating element is greater than or equal to L, we decrement row index. We do this until either row or column index becomes invalid.
2. Next we count the elements which are less than or equal to R. Let’s consider it as count2. We start traversing from the last element of first column and this includes two steps:
• If the current iterating element is less than or equal to R, we increment count2 by corresponding row + 1 as elements in that column above the current element (including current element) must be less than or equal to R. We increment column index.
• If the current iterating element is greater than R, we decrement row index. We do this until either row or column index becomes invalid.
3. Finally, we return the difference of column2 and column1 which will be the required answer.

Below is the implementation of the above approach:

## C++

 `// C++ implementation to count ` `// all elements in a Matrix ` `// which lies in the given range ` ` `  `#include ` `using` `namespace` `std; ` ` `  `#define M 3 ` `#define N 3 ` ` `  `// Counting elements in range [L, R] ` `int` `countElements(``int` `mat[M][N], ` `                  ``int` `L, ``int` `R) ` `{ ` `    ``// Count elements less than L ` `    ``int` `count1 = 0; ` `    ``int` `row = M - 1, col = 0; ` ` `  `    ``while` `(row >= 0 && col < N) { ` ` `  `        ``// Check if the current iterating ` `        ``// element is less than L ` `        ``if` `(mat[row][col] < L) { ` `            ``count1 += (row + 1); ` `            ``col++; ` `        ``} ` `        ``else` `{ ` `            ``row--; ` `        ``} ` `    ``} ` ` `  `    ``// counting elements less ` `    ``// than or equal to R ` `    ``int` `count2 = 0; ` `    ``row = M - 1, col = 0; ` ` `  `    ``while` `(row >= 0 && col < N) { ` ` `  `        ``// Check if the current iterating ` `        ``// element is less than R ` `        ``if` `(mat[row][col] <= R) { ` `            ``count2 += (row + 1); ` `            ``col++; ` `        ``} ` `        ``else` `{ ` `            ``row--; ` `        ``} ` `    ``} ` ` `  `    ``// return the final result ` `    ``return` `count2 - count1; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` ` `  `    ``int` `mat[M][N] = { { 1, 6, 19 }, ` `                      ``{ 2, 7, 31 }, ` `                      ``{ 3, 8, 42 } }; ` ` `  `    ``int` `L = 10, R = 26; ` ` `  `    ``cout << countElements(mat, L, R); ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java implementation to count ` `// all elements in a Matrix ` `// which lies in the given range ` `import` `java.util.*; ` `import` `java.lang.*; ` `class` `GFG{ ` `     `  `static` `int` `N = ``3``; ` `static` `int` `M = ``3``; ` ` `  `// Counting elements in range [L, R] ` `static` `int` `countElements(``int``[][] mat, ` `                         ``int` `L, ``int` `R) ` `{ ` `    ``// Count elements less than L ` `    ``int` `count1 = ``0``; ` `    ``int` `row = M - ``1``, col = ``0``; ` ` `  `    ``while` `(row >= ``0` `&& col < N)  ` `    ``{ ` ` `  `        ``// Check if the current iterating ` `        ``// element is less than L ` `        ``if` `(mat[row][col] < L)  ` `        ``{ ` `            ``count1 += (row + ``1``); ` `            ``col++; ` `        ``} ` `        ``else`  `        ``{ ` `            ``row--; ` `        ``} ` `    ``} ` ` `  `    ``// counting elements less ` `    ``// than or equal to R ` `    ``int` `count2 = ``0``; ` `    ``row = M - ``1``; ` `    ``col = ``0``; ` ` `  `    ``while` `(row >= ``0` `&& col < N)  ` `    ``{ ` ` `  `        ``// Check if the current iterating ` `        ``// element is less than R ` `        ``if` `(mat[row][col] <= R)  ` `        ``{ ` `            ``count2 += (row + ``1``); ` `            ``col++; ` `        ``} ` `        ``else`  `        ``{ ` `            ``row--; ` `        ``} ` `    ``} ` ` `  `    ``// return the final result ` `    ``return` `count2 - count1; ` `} ` ` `  `// Driver code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``int``[][] mat = { { ``1``, ``6``, ``19` `}, ` `                    ``{ ``2``, ``7``, ``31` `}, ` `                    ``{ ``3``, ``8``, ``42` `} }; ` ` `  `    ``int` `L = ``10``, R = ``26``; ` ` `  `    ``System.out.println(countElements(mat, L, R)); ` `} ` `} ` ` `  `// This code is contributed by offbeat `

## Python3

 `# Python3 implementation to count  ` `# all elements in a matrix which  ` `# lies in the given range  ` ` `  `M ``=` `3` `N ``=` `3` ` `  `# Counting elements in range [L, R]  ` `def` `countElements(mat, L, R):  ` ` `  `    ``# Count elements less than L  ` `    ``count1 ``=` `0` `    ``row ``=` `M ``-` `1` `    ``col ``=` `0` ` `  `    ``while` `row >``=` `0` `and` `col < N:  ` ` `  `        ``# Check if the current iterating  ` `        ``# element is less than L  ` `        ``if` `mat[row][col] < L:  ` `            ``count1 ``+``=` `(row ``+` `1``)  ` `            ``col ``+``=` `1` `             `  `        ``else``:  ` `            ``row ``-``=` `1` ` `  `    ``# Counting elements less  ` `    ``# than or equal to R  ` `    ``count2 ``=` `0` `    ``row ``=` `M ``-` `1` `    ``col ``=` `0` ` `  `    ``while` `row >``=` `0` `and` `col < N: ` ` `  `        ``# Check if the current iterating  ` `        ``# element is less than R  ` `        ``if` `mat[row][col] <``=` `R:  ` `            ``count2 ``+``=` `(row ``+` `1``)  ` `            ``col ``+``=` `1` `         `  `        ``else``:  ` `            ``row ``-``=` `1` ` `  `    ``# Return the final result  ` `    ``return` `count2 ``-` `count1  ` ` `  `# Driver code  ` `mat ``=` `[ [ ``1``, ``6``, ``19` `],  ` `        ``[ ``2``, ``7``, ``31` `],  ` `        ``[ ``3``, ``8``, ``42` `] ]  ` `L ``=` `10` `R ``=` `26` ` `  `print``(countElements(mat, L, R))  ` ` `  `# This code is contributed by divyamohan123 `

## C#

 `// C# implementation to count ` `// all elements in a Matrix ` `// which lies in the given range ` `using` `System; ` `class` `GFG{ ` `     `  `static` `int` `N = 3; ` `static` `int` `M = 3; ` ` `  `// Counting elements in range [L, R] ` `static` `int` `countElements(``int``[,] mat, ` `                         ``int` `L, ``int` `R) ` `{ ` `    ``// Count elements less than L ` `    ``int` `count1 = 0; ` `    ``int` `row = M - 1, col = 0; ` ` `  `    ``while` `(row >= 0 && col < N)  ` `    ``{ ` ` `  `        ``// Check if the current iterating ` `        ``// element is less than L ` `        ``if` `(mat[row, col] < L)  ` `        ``{ ` `            ``count1 += (row + 1); ` `            ``col++; ` `        ``} ` `        ``else` `        ``{ ` `            ``row--; ` `        ``} ` `    ``} ` ` `  `    ``// counting elements less ` `    ``// than or equal to R ` `    ``int` `count2 = 0; ` `    ``row = M - 1; ` `    ``col = 0; ` ` `  `    ``while` `(row >= 0 && col < N)  ` `    ``{ ` ` `  `        ``// Check if the current iterating ` `        ``// element is less than R ` `        ``if` `(mat[row, col] <= R)  ` `        ``{ ` `            ``count2 += (row + 1); ` `            ``col++; ` `        ``} ` `        ``else` `        ``{ ` `            ``row--; ` `        ``} ` `    ``} ` ` `  `    ``// return the final result ` `    ``return` `count2 - count1; ` `} ` ` `  `// Driver code ` `public` `static` `void` `Main() ` `{ ` `    ``int``[,] mat = { { 1, 6, 19 }, ` `                   ``{ 2, 7, 31 }, ` `                   ``{ 3, 8, 42 } }; ` ` `  `    ``int` `L = 10, R = 26; ` ` `  `    ``Console.Write(countElements(mat, L, R)); ` `} ` `} ` ` `  `// This code is contributed by Code_Mech `

Output:

```1
```

Time Complexity: O(M + N). M is number of Row and N is number of Column.

Auxiliary Space Complexity: O(1).

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

2

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.