Search in a row wise and column wise sorted matrix
Last Updated :
23 Jul, 2025
Given a matrix mat[][] and an integer x, the task is to check if x is present in mat[][] or not. Every row and column of the matrix is sorted in increasing order.
Examples:
Input: x = 62, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: false
Explanation: 62 is not present in the matrix.
Input: x = 55, mat[][] = [[18, 21, 27],
[38, 55, 67]]
Output: true
Explanation: mat[1][1] is equal to 55.
Input: x = 35, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: true
Explanation: mat[2][0] is equal to 35.
[Naive Approach] Comparing with all elements - O(n*m) Time and O(1) Space
The simple idea is to traverse the complete matrix and search for the target element. If the target element is found, return true. Otherwise, return false.
C++
// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <iostream>
#include <vector>
using namespace std;
bool matSearch(vector<vector<int>> &mat, int x) {
int n = mat.size(), m = mat[0].size();
// Iterate over all the elements to find x
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mat[i][j] == x)
return true;
}
}
// If x was not found, return false
return false;
}
int main() {
vector<vector<int>> mat = {{3, 30, 38},
{20, 52, 54},
{35, 60, 69}};
int x = 35;
if(matSearch(mat, x))
cout << "true";
else
cout << "false";
return 0;
}
Java
// Java program to search an element in row-wise
// and column-wise sorted matrix
class GfG {
static boolean matSearch(int[][] mat, int x) {
int n = mat.length, m = mat[0].length;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mat[i][j] == x)
return true;
}
}
// If x was not found, return false
return false;
}
public static void main(String[] args) {
int[][] mat = {{3, 30, 38},
{20, 52, 54},
{35, 60, 69}};
int x = 35;
if(matSearch(mat, x))
System.out.println("true");
else
System.out.println("false");
}
}
Python
# Python program to search an element in row-wise
# and column-wise sorted matrix
def matSearch(mat, x):
n = len(mat)
m = len(mat[0])
for i in range(n):
for j in range(m):
if mat[i][j] == x:
return True
# If x was not found, return false
return False
if __name__ == "__main__":
mat = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
x = 35
if matSearch(mat, x):
print("true")
else:
print("false")
C#
// C# program to search an element in row-wise
// and column-wise sorted matrix
using System;
class GfG {
static bool matSearch(int[][] mat, int x) {
int n = mat.Length, m = mat[0].Length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == x)
return true;
}
}
// If x was not found, return false
return false;
}
static void Main() {
int[][] mat = new int[][] {
new int[] {3, 30, 38},
new int[] {20, 52, 54},
new int[] {35, 60, 69}
};
int x = 35;
if (matSearch(mat, x))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
JavaScript
// Java Script program to search an element in row-wise
// and column-wise sorted matrix
function matSearch(mat, x) {
const n = mat.length, m = mat[0].length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (mat[i][j] === x)
return true;
}
}
// If x was not found, return false
return false;
}
// Driver Code
const mat = [ [ 3, 30, 38 ],
[ 20, 52, 54 ],
[ 35, 60, 69 ] ];
const x = 35;
if (matSearch(mat, x))
console.log("true");
else
console.log("false");
[Better Approach] Binary Search - O(n*logm) Time and O(1) Space:
To optimize the above approach we are going to use the Binary Search algorithm.
The problem specifies that each row in the given matrix is sorted in ascending order. Instead of searching each column sequentially, we can efficiently apply Binary Search on each row to determine if the target is present.
C++
// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <iostream>
#include <vector>
using namespace std;
bool binarySearch(vector<int> &mat, int target) {
int n = mat.size();
int low = 0, high = n - 1;
// Standard binary search algorithm
while (low <= high) {
int mid = (low + high) / 2;
if (mat[mid] == target)
return true; // Element found
else if (target > mat[mid])
low = mid + 1; // Search in the right half
else
high = mid - 1; // Search in the left half
}
return false; // Element not found
}
bool matSearch(vector<vector<int>> &mat, int x) {
int n = mat.size();
// Iterate over each row and perform binary search
for (int i = 0; i < n; i++) {
if (binarySearch(mat[i], x))
return true; // Element found in one of the rows
}
return false; // Element not found in any row
}
int main() {
vector<vector<int>> mat = {{3, 30, 38},
{20, 52, 54},
{35, 60, 69}};
int x = 35;
if(matSearch(mat, x))
cout << "true";
else
cout << "false";
return 0;
}
Java
// Java program to search an element in row-wise
// and column-wise sorted matrix
class GfG {
public static boolean binarySearch(int[] mat, int target) {
int low = 0, high = mat.length - 1;
// Standard binary search algorithm
while (low <= high) {
int mid = (low + high) / 2;
if (mat[mid] == target)
return true; // Element found
else if (target > mat[mid])
low = mid + 1; // Search in the right half
else
high = mid - 1; // Search in the left half
}
return false; // Element not found
}
static boolean matSearch(int[][] mat, int x) {
int n = mat.length; // Number of rows
// Iterate over each row and perform binary search
for (int i = 0; i < n; i++) {
if (binarySearch(mat[i], x))
return true; // Element found in one of the rows
}
return false; // Element not found in any row
}
public static void main(String[] args) {
int[][] mat = {{3, 30, 38},
{20, 52, 54},
{35, 60, 69}};
int x = 35;
if(matSearch(mat, x))
System.out.println("true");
else
System.out.println("false");
}
}
Python
# Python program to search an element in row-wise
# and column-wise sorted matrix
def binarySearch(mat, target):
n = len(mat)
low, high = 0, n - 1
# Standard binary search algorithm
while low <= high:
mid = (low + high) // 2 # Midpoint index
if mat[mid] == target:
return True # Element found
elif target > mat[mid]:
low = mid + 1 # Search in the right half
else:
high = mid - 1 # Search in the left half
return False # Element not found
def matSearch(mat, x):
n = len(mat)
m = len(mat[0])
# Iterate over each row and perform binary search
for i in range(n):
if binarySearch(mat[i], x):
return True # Element found in one of the rows
return False # Element not found in any row
if __name__ == "__main__":
mat = [
[3, 30, 38],
[20, 52, 54],
[35, 60, 69]
]
x = 35
if matSearch(mat, x):
print("true")
else:
print("false")
C#
// C# program to search an element in row-wise
// and column-wise sorted matrix
using System;
class GfG {
// Function to perform binary search on a sorted row (1D array)
static bool BinarySearch(int[] mat, int target)
{
int low = 0, high = mat.Length - 1;
// Standard binary search algorithm
while (low <= high)
{
int mid = (low + high) / 2;
if (mat[mid] == target)
return true; // Element found
else if (target > mat[mid])
low = mid + 1; // Search in the right half
else
high = mid - 1; // Search in the left half
}
return false; // Element not found
}
// Function to search an element in a row-wise sorted matrix
static bool matSearch(int[][] mat, int x) {
int n = mat.Length;
// Iterate over each row and perform binary search
for (int i = 0; i < n; i++)
{
if (BinarySearch(mat[i], x))
return true; // Element found in one of the rows
}
return false; // Element not found in any row
}
static void Main() {
int[][] mat = new int[][] {
new int[] {3, 30, 38},
new int[] {20, 52, 54},
new int[] {35, 60, 69}
};
int x = 35;
if (matSearch(mat, x))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
JavaScript
// JavaScript program to search an element in row-wise
// and column-wise sorted matrix
function binarySearch(mat, target) {
let low = 0, high = mat.length - 1;
// Standard binary search algorithm
while (low <= high) {
let mid = Math.floor((low + high) / 2); // Use Math.floor() to get an integer index
if (mat[mid] === target)
return true; // Element found
else if (target > mat[mid])
low = mid + 1; // Search in the right half
else
high = mid - 1; // Search in the left half
}
return false; // Element not found
}
function matSearch(mat, x) {
let n = mat.length;
// Iterate over each row and perform binary search
for (let i = 0; i < n; i++) {
if (binarySearch(mat[i], x))
return true; // Element found in one of the rows
}
return false; // Element not found in any row
}
// Driver Code
let mat = [
[3, 30, 38],
[20, 52, 54],
[35, 60, 69]
];
let x = 35;
if (matSearch(mat, x))
console.log("true");
else
console.log("false");
[Expected Approach] Eliminating rows or columns - O(n + m) Time and O(1) Space:
The idea is to remove a row or column in each comparison until an element is found. Start searching from the top-right corner of the matrix. There are 3 possible cases:
- x is greater than the current element: This ensures that all the elements in the current row are smaller than the given number as the pointer is already at the right-most element and the row is sorted. Thus, the entire row gets eliminated and continues the search from the next row.
- x is smaller than the current element: This ensures that all the elements in the current column are greater than the given number. Thus, the entire column gets eliminated and continues the search from the previous column, i.e. the column on the immediate left.
- The given number is equal to the current number: This will end the search.
Illustration:
C++
// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <iostream>
#include <vector>
using namespace std;
bool matSearch(vector<vector<int>> &mat, int x) {
int n = mat.size(), m = mat[0].size();
int i = 0, j = m - 1;
while(i < n && j >= 0) {
// If x > mat[i][j], then x will be greater
// than all elements to the left of
// mat[i][j] in row i, so increment i
if(x > mat[i][j]) {
i++;
}
// If x < mat[i][j], then x will be smaller
// than all elements to the bottom of
// mat[i][j] in column j, so decrement j
else if(x < mat[i][j]) {
j--;
}
// If x = mat[i][j], return true
else {
return true;
}
}
// If x was not found, return false
return false;
}
int main() {
vector<vector<int>> mat = {{3, 30, 38},
{20, 52, 54},
{35, 60, 69}};
int x = 35;
if(matSearch(mat, x))
cout << "true";
else
cout << "false";
return 0;
}
Java
// Java program to search an element in row-wise
// and column-wise sorted matrix
import java.util.*;
class GfG {
static boolean matSearch(int[][] mat, int x) {
int n = mat.length, m = mat[0].length;
int i = 0, j = m - 1;
while (i < n && j >= 0) {
// If x > mat[i][j], then x will be greater
// than all elements to the left of
// mat[i][j] in row i, so increment i
if (x > mat[i][j]) {
i++;
}
// If x < mat[i][j], then x will be smaller
// than all elements to the bottom of
// mat[i][j] in column j, so decrement j
else if (x < mat[i][j]) {
j--;
}
// If x = mat[i][j], return true
else {
return true;
}
}
// If x was not found, return false
return false;
}
public static void main(String[] args) {
int[][] mat = {
{3, 30, 38},
{20, 52, 54},
{35, 60, 69}
};
int x = 35;
if (matSearch(mat, x))
System.out.println("true");
else
System.out.println("false");
}
}
Python
# Python program to search an element in row-wise
# and column-wise sorted matrix
def matSearch(mat, x):
n = len(mat)
m = len(mat[0])
i = 0
j = m - 1
while i < n and j >= 0:
# If x > mat[i][j], then x will be greater
# than all elements to the left of
# mat[i][j] in row i, so increment i
if x > mat[i][j]:
i += 1
# If x < mat[i][j], then x will be smaller
# than all elements to the bottom of
# mat[i][j] in column j, so decrement j
elif x < mat[i][j]:
j -= 1
# If x = mat[i][j], return true
else:
return True
# If x was not found, return false
return False
if __name__ == "__main__":
mat = [
[3, 30, 38],
[20, 52, 54],
[35, 60, 69]
]
x = 35
if matSearch(mat, x):
print("true")
else:
print("false")
C#
// C# program to search an element in row-wise
// and column-wise sorted matrix
using System;
class GfG {
static bool matSearch(int[][] mat, int x) {
int n = mat.Length, m = mat[0].Length;
int i = 0, j = m - 1;
while (i < n && j >= 0) {
// If x > mat[i][j], then x will be greater
// than all elements to the left of
// mat[i][j] in row i, so increment i
if (x > mat[i][j]) {
i++;
}
// If x < mat[i][j], then x will be smaller
// than all elements to the bottom of
// mat[i][j] in column j, so decrement j
else if (x < mat[i][j]) {
j--;
}
// If x = mat[i][j], return true
else {
return true;
}
}
// If x was not found, return false
return false;
}
static void Main() {
int[][] mat = new int[][] {
new int[] {3, 30, 38},
new int[] {20, 52, 54},
new int[] {35, 60, 69}
};
int x = 35;
if (matSearch(mat, x))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
JavaScript
// JavaScript program to search an element in row-wise
// and column-wise sorted matrix
function matSearch(mat, x) {
let n = mat.length, m = mat[0].length;
let i = 0, j = m - 1;
while (i < n && j >= 0) {
// If x > mat[i][j], then x will be greater
// than all elements to the left of
// mat[i][j] in row i, so increment i
if (x > mat[i][j]) {
i++;
}
// If x < mat[i][j], then x will be smaller
// than all elements to the bottom of
// mat[i][j] in column j, so decrement j
else if (x < mat[i][j]) {
j--;
}
// If x = mat[i][j], return true
else {
return true;
}
}
// If x was not found, return false
return false;
}
// Driver Code
let mat = [
[3, 30, 38],
[20, 52, 54],
[35, 60, 69]
];
let x = 35;
if (matSearch(mat, x))
console.log("true");
else
console.log("false");
Related Article: Search element in a sorted matrix
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem