Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Heap
  • Practice Heap
  • MCQs on Heap
  • Heap Tutorial
  • Binary Heap
  • Building Heap
  • Binomial Heap
  • Fibonacci Heap
  • Heap Sort
  • Heap vs Tree
  • Leftist Heap
  • K-ary Heap
  • Advantages & Disadvantages
Open In App
Next Article:
Find common elements in three sorted arrays
Next article icon

Kth smallest element in a row-wise and column-wise sorted 2D array

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an n x n matrix, every row and column is sorted in non-decreasing order. Given a number K where K lies in the range [1, n*n], find the Kth smallest element in the given 2D matrix.

Example:

Input: mat ={{10, 20, 30, 40},
{15, 25, 35, 45},
{24, 29, 37, 48},
{32, 33, 39, 50 }}
K = 3
Output: 20
Explanation: The 3rd smallest element is 20


Input: mat ={{10, 20, 30, 40},
{15, 25, 35, 45},
{24, 29, 37, 48},
{32, 33, 39, 50 }}
K = 7
Output: 30
Explanation: The 7th smallest element is 30

Table of Content

  • [Naive Approach] – Using Sorting – O(N2 * log(N2)) Time and O(N) Space
  • [Naive Approach] – Using Priority Queue – O(N2 * log(K)) Time and O(K) Space
  • [Expected Approach] – Binary Search on Range – O(N* log(Max-Min)) Time and O(1) Space

[Naive Approach] – Using Sorting – O(N2 * log(N2)) Time and O(N) Space

Initialize a 1-dimensional array of size n*n to store all the elements of the mat[][] , we will get our kth minimum element by sorting the 1-dimensional array in non-decreasing order.

Below is the implementation of the above approach:

C++
//C++ program to find the Kth smallest element #include <bits/stdc++.h> #include <iostream> using namespace std;  // Function to find the kth smallest element in a sorted 2D // matrix int findKthSmallest(vector<vector<int> >& matrix, int k) {     int n = matrix.size();      // Create a vector to store all elements     vector<int> elements;      // Store all elements of the matrix into the vector     for (int i = 0; i < n; ++i) {         for (int j = 0; j < n; ++j) {             elements.push_back(matrix[i][j]);         }     }      // Sort the vector     sort(elements.begin(), elements.end());      // Return the kth smallest element (1-based index, hence     // k-1)     return elements[k - 1]; }  int main() {     // Define the sorted 2D matrix     vector<vector<int> > matrix         = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };     int k = 8;     int result = findKthSmallest(matrix, k);      cout << "The " << k          << "th smallest element is: " << result << endl;      return 0; } 
Java
//Java program to find the Kth smallest element  import java.util.ArrayList; import java.util.Collections; import java.util.List;  public class GFG {      // Function to find the kth smallest element in a sorted 2D matrix     public static int findKthSmallest(int[][] matrix, int k) {         int n = matrix.length;          // Create a list to store all elements         List<Integer> elements = new ArrayList<>();          // Store all elements of the matrix into the list         for (int i = 0; i < n; i++) {             for (int j = 0; j < n; j++) {                 elements.add(matrix[i][j]);             }         }          // Sort the list         Collections.sort(elements);          // Return the kth smallest element (1-based index, hence k-1)         return elements.get(k - 1);     }      public static void main(String[] args) {         // Define the sorted 2D matrix         int[][] matrix = {             {1, 5, 9},             {10, 11, 13},             {12, 13, 15}         };          // Find the 8th smallest element         int k = 8;         int result = findKthSmallest(matrix, k);          System.out.println("The " + k + "th smallest element is: " + result);     } } 
Python
#Python program to find the Kth smallest element  def find_kth_smallest(matrix, k):     # Create a list to store all elements     elements = []      # Store all elements of the matrix into the list     for row in matrix:         elements.extend(row)      # Sort the list     elements.sort()      # Return the kth smallest element (1-based index, hence k-1)     return elements[k - 1]   # Define the sorted 2D matrix matrix = [     [1, 5, 9],     [10, 11, 13],     [12, 13, 15] ]  # Find the 8th smallest element k = 8 result = find_kth_smallest(matrix, k)  print(f"The {k}th smallest element is: {result}") 
C#
//C# program to find the Kth smallest element using System; using System.Collections.Generic;  class Program {     // Function to find the kth smallest element in a sorted 2D matrix     static int FindKthSmallest(int[,] matrix, int k)     {         int n = matrix.GetLength(0);          // Create a list to store all elements         List<int> elements = new List<int>();          // Store all elements of the matrix into the list         for (int i = 0; i < n; i++)         {             for (int j = 0; j < n; j++)             {                 elements.Add(matrix[i, j]);             }         }          // Sort the list         elements.Sort();          // Return the kth smallest element (1-based index, hence k-1)         return elements[k - 1];     }      static void Main()     {         // Define the sorted 2D matrix         int[,] matrix = {             { 1, 5, 9 },             { 10, 11, 13 },             { 12, 13, 15 }         };          // Find the 8th smallest element         int k = 8;         int result = FindKthSmallest(matrix, k);          // Use traditional string concatenation instead of string interpolation         Console.WriteLine("The " + k + "th smallest element is: " + result);     } } 
JavaScript
// Javascript program to find the Kth smallest element function findKthSmallest(matrix, k) {     // Create an array to store all elements     let elements = [];      // Store all elements of the matrix into the array     for (let row of matrix) {         elements.push(...row);     }      // Sort the array     elements.sort((a, b) => a - b);      // Return the kth smallest element (1-based index, hence     // k-1)     return elements[k - 1]; }  // Define the sorted 2D matrix const matrix =     [ [ 1, 5, 9 ], [ 10, 11, 13 ], [ 12, 13, 15 ] ];  // Find the 8th smallest element const k = 8; const result = findKthSmallest(matrix, k);  console.log(`The ${k}th smallest element is: ${result}`); 

Output
The 8th smallest element is: 13 

Time Complexity: O(N2 * log(N2)) , due to sorting of N2 elements.
Auxiliary Space :  O(N2)

[Expected Approach] – Using Priority Queue – O(N2 * log(K)) Time and O(K) Space

Create a priority_queue, say max-heap to store and maintain the track of K elements in the heap. If the size of the heap exceeds more than K while inserting the elements , we will pop the top element from max-heap so as to maintain the size of K elements. After successful traversal in mat[][], the top element of the max_heap will be the Kth minimum element.

Below is the implementation of the above approach:

C++
//C++ program to find the Kth smallest element using priority queue #include <bits/stdc++.h> #include <iostream>  using namespace std;  // Function to find the kth smallest element in a sorted 2D // matrix using a max-heap int findKthSmallest(vector<vector<int> >& matrix, int k) {     int n = matrix.size();     priority_queue<int> maxHeap;      // Traverse all elements in the matrix     for (int i = 0; i < n; ++i) {         for (int j = 0; j < n; ++j) {             int currentElement = matrix[i][j];              // Push the current element into the max-heap             maxHeap.push(currentElement);              // If the size of the max-heap exceeds k, remove             // the largest element             if (maxHeap.size() > k) {                 maxHeap.pop();             }         }     }      // The top element of the max-heap is the kth smallest     // element     return maxHeap.top(); }  int main() {     // Define the sorted 2D matrix     vector<vector<int> > matrix         = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };      // Find the 8th smallest element     int k = 8;     int result = findKthSmallest(matrix, k);      cout << "The " << k          << "th smallest element is: " << result << endl;      return 0; } 
Java
//Java program to find the Kth smallest element using priority queue import java.util.PriorityQueue;  public class GFG {      // Function to find the kth smallest element in a sorted     // 2D matrix using a max-heap     public static int findKthSmallest(int[][] matrix, int k)     {         int n = matrix.length;         // Max-heap to store k smallest elements         PriorityQueue<Integer> maxHeap             = new PriorityQueue<>((a, b) -> b - a);          // Traverse all elements in the matrix         for (int i = 0; i < n; i++) {             for (int j = 0; j < n; j++) {                 int currentElement = matrix[i][j];                  // Push the current element into the                 // max-heap                 maxHeap.offer(currentElement);                  // If the size of the max-heap exceeds k,                 // remove the largest element                 if (maxHeap.size() > k) {                     maxHeap.poll();                 }             }         }          // The top element of the max-heap is the kth         // smallest element         return maxHeap.peek();     }      public static void main(String[] args)     {         // Define the sorted 2D matrix         int[][] matrix = { { 1, 5, 9 },                            { 10, 11, 13 },                            { 12, 13, 15 } };          // Find the 8th smallest element         int k = 8;         int result = findKthSmallest(matrix, k);          System.out.println("The " + k                            + "th smallest element is: "                            + result);     } } 
Python
#Python program to find the Kth smallest element using priority queue import heapq   def find_kth_smallest(matrix, k):     n = len(matrix)     # Max-heap to store k smallest elements     max_heap = []      # Traverse all elements in the matrix     for i in range(n):         for j in range(n):             current_element = matrix[i][j]              # Push the current element into the max-heap             heapq.heappush(max_heap, -current_element)              # If the size of the max-heap exceeds k, remove the largest element             if len(max_heap) > k:                 heapq.heappop(max_heap)      # The top element of the max-heap is the kth smallest element     return -max_heap[0]   # Define the sorted 2D matrix matrix = [     [1, 5, 9],     [10, 11, 13],     [12, 13, 15] ]  # Find the 8th smallest element k = 8 result = find_kth_smallest(matrix, k)  print(f"The {k}th smallest element is: {result}") 
C#
//C# program to find the Kth smallest element using priority queue using System; using System.Collections.Generic;  class MaxHeap<T> where T : IComparable<T> {     private readonly List<T> _heap;     private readonly int _capacity;      public MaxHeap(int capacity)     {         _heap = new List<T>(capacity);         _capacity = capacity;     }      public int Count => _heap.Count;      public void Add(T item)     {         if (_heap.Count < _capacity)         {             _heap.Add(item);             HeapifyUp(_heap.Count - 1);         }         else if (_heap.Count > 0 && item.CompareTo(_heap[0]) < 0)         {             _heap[0] = item;             HeapifyDown(0);         }     }      public T Peek()     {         if (_heap.Count == 0)             throw new InvalidOperationException("Heap is empty.");         return _heap[0];     }      private void HeapifyUp(int index)     {         int parentIndex = (index - 1) / 2;         if (index > 0 && _heap[index].CompareTo(_heap[parentIndex]) > 0)         {             Swap(index, parentIndex);             HeapifyUp(parentIndex);         }     }      private void HeapifyDown(int index)     {         int leftChild = 2 * index + 1;         int rightChild = 2 * index + 2;         int largest = index;          if (leftChild < _heap.Count && _heap[leftChild].CompareTo(_heap[largest]) > 0)         {             largest = leftChild;         }          if (rightChild < _heap.Count && _heap[rightChild].CompareTo(_heap[largest]) > 0)         {             largest = rightChild;         }          if (largest != index)         {             Swap(index, largest);             HeapifyDown(largest);         }     }      private void Swap(int i, int j)     {         T temp = _heap[i];         _heap[i] = _heap[j];         _heap[j] = temp;     } }  class Program {     // Function to find the kth smallest element in a sorted 2D matrix using a max-heap     static int FindKthSmallest(int[,] matrix, int k)     {         int n = matrix.GetLength(0);         // Max-heap to store k smallest elements         var maxHeap = new MaxHeap<int>(k);          // Traverse all elements in the matrix         for (int i = 0; i < n; ++i)         {             for (int j = 0; j < n; ++j)             {                 int currentElement = matrix[i, j];                 maxHeap.Add(currentElement);             }         }          // The top element of the max-heap is the kth smallest element         return maxHeap.Peek();     }      static void Main()     {         // Define the sorted 2D matrix         int[,] matrix = {             { 1, 5, 9 },             { 10, 11, 13 },             { 12, 13, 15 }         };          // Find the 8th smallest element         int k = 8;         int result = FindKthSmallest(matrix, k);          Console.WriteLine($"The {k}th smallest element is: {result}");     } } 
JavaScript
//Javascript program to find the Kth smallest element using priority queue class MaxHeap {     constructor() {         this.heap = [];     }      push(val) {         this.heap.push(val);         this._heapifyUp(this.heap.length - 1);     }      pop() {         if (this.heap.length === 0) return null;         const root = this.heap[0];         const end = this.heap.pop();         if (this.heap.length > 0) {             this.heap[0] = end;             this._heapifyDown(0);         }         return root;     }      peek() {         return this.heap[0] || null;     }      _heapifyUp(index) {         const element = this.heap[index];         while (index > 0) {             const parentIndex = Math.floor((index - 1) / 2);             const parent = this.heap[parentIndex];             if (parent >= element) break;             this.heap[index] = parent;             index = parentIndex;         }         this.heap[index] = element;     }      _heapifyDown(index) {         const length = this.heap.length;         const element = this.heap[index];         while (true) {             const leftChildIdx = 2 * index + 1;             const rightChildIdx = 2 * index + 2;             let largest = index;             if (leftChildIdx < length && this.heap[leftChildIdx] > this.heap[largest]) {                 largest = leftChildIdx;             }             if (rightChildIdx < length && this.heap[rightChildIdx] > this.heap[largest]) {                 largest = rightChildIdx;             }             if (largest === index) break;             this.heap[index] = this.heap[largest];             index = largest;         }         this.heap[index] = element;     } }  // Function to find the kth smallest element in a sorted 2D matrix using a max-heap function findKthSmallest(matrix, k) {     const n = matrix.length;     const maxHeap = new MaxHeap();      for (let i = 0; i < n; ++i) {         for (let j = 0; j < n; ++j) {             const currentElement = matrix[i][j];             maxHeap.push(currentElement);              if (maxHeap.heap.length > k) {                 maxHeap.pop();             }         }     }      return maxHeap.peek(); }  // Example usage const matrix = [     [1, 5, 9],     [10, 11, 13],     [12, 13, 15] ]; const k = 8; const result = findKthSmallest(matrix, k);  console.log(`The ${k}th smallest element is: ${result}`); 

Output
The 8th smallest element is: 13 

Time Complexity: O(N2* log(K)) , we will be inserting all the elements in heap one by one by maintaining the size of K elements.
Auxiliary Space : O(K)

[Expected Approach for Small Range] – Binary Search on Range – O(N* log(Max-Min)) Time and O(1) Space

This approach uses binary search to iterate over possible solutions. As answer lies in the range from mat[0][0] to mat[N-1][N-1], So we do a binary search on this range and in each  iteration determine the no of elements smaller than or equal to our current middle element.

Kth-smallest-element-in-a-row-wise-and-column-wise-sorted-2D-array



Follow the steps below to solve the problem:

  • Initialize a variable, say low equals to the mat[0][0] (minimum value of matrix).
  • Initialize a variable, say high equals to the mat[n-1][n-1] (maximum value of matrix).
  • Initialize ans to 0.
  • Perform Binary Search on the range from low to high:
    • Calculate the midpoint in the range say mid.
    • If the CountSmallerEqual(function which will return the count of elements less than or equal to mid) is less than k, update low to mid+ 1.
    • if the returned value is greater or equal to K , this can be our possible ans. So, update ans to mid and narrow the search range by setting high to mid – 1.
  • CountSmallerEqual Function (Helper function that counts the number of elements in the matrix less than or equal to the given mid.)
    • Initialize a pointer, say row and col points to 0 and n-1 respectively. And a variable count = 0.
    • If the mat[row][col] is greater than mid, move left in the matrix by decrementing col.
    • If the mat[row][col] is less than or equal to mid, increment the count as count += col+ 1 and move down in the matrix by incrementing row.

Below is the implementation of the above approach:

C++
//C++ program to find the Kth smallest element using Binary Serach #include <iostream> #include <vector>  using namespace std;  // Function to count the number of elements less than or equal to x int countSmallerEqual(const vector<vector<int>>& matrix, int x) {     int n = matrix.size();     int count = 0;     int row = 0;     int col = n - 1;      // Traverse from the top-right corner     while (row < n && col >= 0) {         if (matrix[row][col] <= x) {             // If current element is less than or equal to x,             // all elements in this row up to the current column are <= x             count += (col + 1);             row++;         } else {             // Move left in the matrix             col--;         }     }      return count; }  // Function to find the Kth smallest element in a sorted 2D matrix using binary search int findKthSmallest(const vector<vector<int>>& matrix, int k) {     int n = matrix.size();     int low = matrix[0][0];     int high = matrix[n - 1][n - 1];     int ans = 0;      while (low <= high) {         int mid = low + (high - low) / 2;                  // Count elements less than or equal to mid         int count = countSmallerEqual(matrix, mid);          if (count < k) {             // If there are less than k elements <= mid, the kth smallest is larger             low = mid + 1;         } else {             // Otherwise, mid might be the answer, but we need to check for smaller values             ans = mid;             high = mid - 1;         }     }      return ans; }  int main() {     // Define the sorted 2D matrix     vector<vector<int>> matrix = {         {1, 5, 9},         {10, 11, 13},         {12, 13, 15}     };          // Find the Kth smallest element     int k = 8;     int result = findKthSmallest(matrix, k);          cout << "The " << k << "th smallest element is: " << result << endl;          return 0; } 
Java
//Java program to find the Kth smallest element using Binary Serach  import java.util.Arrays;  public class GFG {          // Function to count the number of elements less than or equal to x     public static int countSmallerEqual(int[][] matrix, int x) {         int n = matrix.length;         int count = 0;         int row = 0;         int col = n - 1;          // Traverse from the top-right corner         while (row < n && col >= 0) {             if (matrix[row][col] <= x) {                 // If current element is less than or equal to x,                 // all elements in this row up to the current column are <= x                 count += (col + 1);                 row++;             } else {                 // Move left in the matrix                 col--;             }         }          return count;     }      // Function to find the Kth smallest element in a sorted 2D matrix using binary search     public static int findKthSmallest(int[][] matrix, int k) {         int n = matrix.length;         int low = matrix[0][0];         int high = matrix[n - 1][n - 1];         int ans = 0;          while (low <= high) {             int mid = low + (high - low) / 2;                          // Count elements less than or equal to mid             int count = countSmallerEqual(matrix, mid);              if (count < k) {                 // If there are less than k elements <= mid, the kth smallest is larger                 low = mid + 1;             } else {                 // Otherwise, mid might be the answer, but we need to check for smaller values                 ans = mid;                 high = mid - 1;             }         }          return ans;     }      public static void main(String[] args) {         // Define the sorted 2D matrix         int[][] matrix = {             {1, 5, 9},             {10, 11, 13},             {12, 13, 15}         };                  // Find the Kth smallest element         int k = 8;         int result = findKthSmallest(matrix, k);                  System.out.println("The " + k + "th smallest element is: " + result);     } } 
Python
#Python program to find the Kth smallest element using Binary Serach  def count_smaller_equal(matrix, x):     n = len(matrix)     count = 0     row, col = 0, n - 1      # Traverse from the top-right corner     while row < n and col >= 0:         if matrix[row][col] <= x:             # If current element is less than or equal to x,             # all elements in this row up to the current column are <= x             count += (col + 1)             row += 1         else:             # Move left in the matrix             col -= 1      return count  def find_kth_smallest(matrix, k):     n = len(matrix)     low, high = matrix[0][0], matrix[n - 1][n - 1]     ans = 0      while low <= high:         mid = low + (high - low) // 2                  # Count elements less than or equal to mid         count = count_smaller_equal(matrix, mid)          if count < k:             # If there are less than k elements <= mid, the kth smallest is larger             low = mid + 1         else:             # Otherwise, mid might be the answer, but we need to check for smaller values             ans = mid             high = mid - 1      return ans  # Define the sorted 2D matrix matrix = [     [1, 5, 9],     [10, 11, 13],     [12, 13, 15] ]  # Find the Kth smallest element k = 8 result = find_kth_smallest(matrix, k)  print(f"The {k}th smallest element is: {result}") 
C#
//C# program to find the Kth smallest element using Binary Serach  using System;  class GFG {     // Function to count the number of elements less than or equal to x     static int CountSmallerEqual(int[,] matrix, int x) {         int n = matrix.GetLength(0);         int count = 0;         int row = 0;         int col = n - 1;          // Traverse from the top-right corner         while (row < n && col >= 0) {             if (matrix[row, col] <= x) {                 // If current element is less than or equal to x,                 // all elements in this row up to the current column are <= x                 count += (col + 1);                 row++;             } else {                 // Move left in the matrix                 col--;             }         }          return count;     }      // Function to find the Kth smallest element in a sorted 2D matrix using binary search     static int FindKthSmallest(int[,] matrix, int k) {         int n = matrix.GetLength(0);         int low = matrix[0, 0];         int high = matrix[n - 1, n - 1];         int ans = 0;          while (low <= high) {             int mid = low + (high - low) / 2;                          // Count elements less than or equal to mid             int count = CountSmallerEqual(matrix, mid);              if (count < k) {                 // If there are less than k elements <= mid, the kth smallest is larger                 low = mid + 1;             } else {                 // Otherwise, mid might be the answer, but we need to check for smaller values                 ans = mid;                 high = mid - 1;             }         }          return ans;     }      static void Main() {         // Define the sorted 2D matrix         int[,] matrix = {             {1, 5, 9},             {10, 11, 13},             {12, 13, 15}         };                  // Find the Kth smallest element         int k = 8;         int result = FindKthSmallest(matrix, k);                  Console.WriteLine("The " + k + "th smallest element is: " + result);     } } 
JavaScript
//Javascript program to find the Kth smallest element using Binary Serach  function countSmallerEqual(matrix, x) {     const n = matrix.length;     let count = 0;     let row = 0;     let col = n - 1;      // Traverse from the top-right corner     while (row < n && col >= 0) {         if (matrix[row][col] <= x) {             // If current element is less than or equal to x,             // all elements in this row up to the current column are <= x             count += (col + 1);             row++;         } else {             // Move left in the matrix             col--;         }     }      return count; }  function findKthSmallest(matrix, k) {     const n = matrix.length;     let low = matrix[0][0];     let high = matrix[n - 1][n - 1];     let ans = 0;      while (low <= high) {         let mid = Math.floor(low + (high - low) / 2);                  // Count elements less than or equal to mid         let count = countSmallerEqual(matrix, mid);          if (count < k) {             // If there are less than k elements <= mid, the kth smallest is larger             low = mid + 1;         } else {             // Otherwise, mid might be the answer, but we need to check for smaller values             ans = mid;             high = mid - 1;         }     }      return ans; }  // Define the sorted 2D matrix const matrix = [     [1, 5, 9],     [10, 11, 13],     [12, 13, 15] ];  // Find the Kth smallest element const k = 8; const result = findKthSmallest(matrix, k);  console.log(`The ${k}th smallest element is: ${result}`); 

Output
The 8th smallest element is: 13 

Time Complexity: O(2*N* log(MAX – MIN)) , where MAX and MIN are the maximum and minimum element in 2d matrix.
Auxiliary Space : O(1)



Next Article
Find common elements in three sorted arrays

A

Aarti_Rathi
Improve
Article Tags :
  • DSA
  • Heap
  • Matrix
  • Searching
  • Accolite
  • Amazon
  • Order-Statistics
Practice Tags :
  • Accolite
  • Amazon
  • Heap
  • Matrix
  • Searching

Similar Reads

  • Searching Algorithms
    Searching 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
    3 min read
  • Most Common Searching Algorithms

    • Linear Search Algorithm
      Given an array, arr of n integers, and an integer element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesn't exist. Input: arr[] = [1, 2, 3, 4], x = 3Output: 2Explanation: There is one test case with array as [1, 2, 3 4]
      9 min read

    • Binary Search Algorithm - Iterative and Recursive Implementation
      Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
      15+ min read

    Other Searching Algorithms

    • Sentinel Linear Search
      Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. In a traditional linear search, only N comparisons are made, and in a Sentinel Linear Search, the sentinel value is used to avoid any out-of-b
      7 min read

    • Meta Binary Search | One-Sided Binary Search
      Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta B
      9 min read

    • Ternary Search
      Computer systems use different methods to find specific data. There are various search algorithms, each better suited for certain situations. For instance, a binary search divides information into two parts, while a ternary search does the same but into three equal parts. It's worth noting that tern
      15+ min read

    • Jump Search
      Like Binary Search, Jump Search is a searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements.For example, suppose we have an array arr[] of size n and a block (t
      11 min read

    • Interpolation Search
      Given a sorted array of n uniformly distributed values arr[], write a function to search for a particular element x in the array. Linear Search finds the element in O(n) time, Jump Search takes O(n) time and Binary Search takes O(log n) time. The Interpolation Search is an improvement over Binary Se
      15+ min read

    • Exponential Search
      The name of this searching algorithm may be misleading as it works in O(Log n) time. The name comes from the way it searches an element. Given a sorted array, and an element x to be searched, find position of x in the array. Input: arr[] = {10, 20, 40, 45, 55} x = 45Output: Element found at index 3I
      15+ min read

    • Fibonacci Search
      Given a sorted array arr[] of size n and an integer x. Your task is to check if the integer x is present in the array arr[] or not. Return index of x if it is present in array else return -1. Examples: Input: arr[] = [2, 3, 4, 10, 40], x = 10Output: 3Explanation: 10 is present at index 3. Input: arr
      11 min read

    • The Ubiquitous Binary Search | Set 1
      We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, "I sincerely attempt to solve the problem and ensure th
      15+ min read

    Comparisons between Searching Algorithms

    • Linear Search vs Binary Search
      Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position
      11 min read

    • Interpolation search vs Binary search
      Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-k
      7 min read

    • Why is Binary Search preferred over Ternary Search?
      The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1
      11 min read

    • Is Sentinel Linear Search better than normal Linear Search?
      Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to
      8 min read

    Library implementations of Searching algorithms

    • Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
      In C++, STL provide various functions like std::binary_search(), std::lower_bound(), and std::upper_bound() which uses the the binary search algorithm for different purposes. These function will only work on the sorted data. There are the 3 binary search function in C++ STL: Table of Content binary_
      3 min read

    • Arrays.binarySearch() in Java with Examples | Set 1
      In Java, the Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted by the Arrays.sort() method before making this call. If it is not sorted, the results are undefined. Example: Below is a s
      3 min read

    • Arrays.binarySearch() in Java with examples | Set 2 (Search in subarray)
      Arrays.binarySearch()| Set 1 Covers how to find an element in a sorted array in Java. This set will cover "How to Search a key in an array within a given range including only start index". Syntax : public static int binarySearch(data_type[] arr, int fromIndex, int toIndex, data_type key) Parameters
      5 min read

    • Collections.binarySearch() in Java with Examples
      java.util.Collections.binarySearch() method is a java.util.Collections class method that returns the position of an object in a sorted list. // Returns index of key in a sorted list sorted in// ascending orderpublic static int binarySearch(List slist, T key)// Returns index of key in a sorted list s
      4 min read

    Easy problems on Searching algorithms

    • Find the Missing Number
      Given an array arr[] of size n-1 with distinct integers in the range of [1, n]. This array represents a permutation of the integers from 1 to n with one element missing. Find the missing element in the array. Examples: Input: arr[] = [8, 2, 4, 5, 3, 7, 1]Output: 6Explanation: All the numbers from 1
      12 min read

    • Find the first repeating element in an array of integers
      Given an array of integers arr[], The task is to find the index of first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. Examples: Input: arr[] = {10, 5, 3, 4, 3, 5, 6}Output: 5 Explanation: 5 is the first element that repe
      8 min read

    • Missing and Repeating in an Array
      Given an unsorted array of size n. Array elements are in the range of 1 to n. One number from set {1, 2, ...n} is missing and one number occurs twice in the array. The task is to find these two numbers. Examples: Input: arr[] = {3, 1, 3}Output: 3, 2Explanation: In the array, 2 is missing and 3 occur
      15+ min read

    • Count 1's in a sorted binary array
      Given a binary array arr[] of size n, which is sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = [1, 1, 0, 0, 0, 0, 0]Output: 2Explanation: Count of the 1's in the given array is 2. Input: arr[] = [1, 1, 1, 1, 1, 1, 1]Output: 7 Input: arr[] = [0, 0, 0, 0, 0, 0,
      8 min read

    • Two Sum - Pair Closest to 0
      Given an integer array arr[], the task is to find the maximum sum of two elements such that sum is closest to zero. Note: In case if we have two of more ways to form sum of two elements closest to zero return the maximum sum.Examples: Input: arr[] = [-8, 5, 2, -6]Output: -1Explanation: The min absol
      15+ min read

    • Pair with the given difference
      Given an unsorted array and an integer x, the task is to find if there exists a pair of elements in the array whose absolute difference is x. Examples: Input: arr[] = [5, 20, 3, 2, 50, 80], x = 78Output: YesExplanation: The pair is {2, 80}. Input: arr[] = [90, 70, 20, 80, 50], x = 45Output: NoExplan
      14 min read

    • Kth smallest element in a row-wise and column-wise sorted 2D array
      Given an n x n matrix, every row and column is sorted in non-decreasing order. Given a number K where K lies in the range [1, n*n], find the Kth smallest element in the given 2D matrix. Example: Input: mat ={{10, 20, 30, 40}, {15, 25, 35, 45}, {24, 29, 37, 48}, {32, 33, 39, 50 }}K = 3Output: 20Expla
      15+ min read

    • Find common elements in three sorted arrays
      Given three sorted arrays in non-decreasing order, print all common elements in non-decreasing order across these arrays. If there are no such elements return an empty array. In this case, the output will be -1. Note: In case of duplicate common elements, print only once. Examples: Input: arr1[] = [
      12 min read

    • Ceiling in a sorted array
      Given a sorted array and a value x, find index of the ceiling of x. The ceiling of x is the smallest element in an array greater than or equal to x. Note: In case of multiple occurrences of ceiling of x, return the index of the first occurrence. Examples : Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x
      13 min read

    • Floor in a Sorted Array
      Given a sorted array and a value x, find the element of the floor of x. The floor of x is the largest element in the array smaller than or equal to x. Examples: Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5Output: 1Explanation: Largest number less than or equal to 5 is 2, whose index is 1 Input: a
      9 min read

    • Bitonic Point - Maximum in Increasing Decreasing Array
      Given an array arr[] of integers which is initially strictly increasing and then strictly decreasing, the task is to find the bitonic point, that is the maximum value in the array. Note: Bitonic Point is a point in bitonic sequence before which elements are strictly increasing and after which elemen
      11 min read

    • Given Array of size n and a number k, find all elements that appear more than n/k times
      Given an array of size n and an integer k, find all elements in the array that appear more than n/k times. Examples: Input: arr[ ] = [3, 4, 2, 2, 1, 2, 3, 3], k = 4Output: [2, 3]Explanation: Here n/k is 8/4 = 2, therefore 2 appears 3 times in the array that is greater than 2 and 3 appears 3 times in
      15+ min read

    Medium problems on Searching algorithms

    • 3 Sum - Find All Triplets with Zero Sum
      Given an array arr[], the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to zero and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted order, i.e., i < j < k. E
      11 min read

    • Find the element before which all the elements are smaller than it, and after which all are greater
      Given an array, find an element before which all elements are equal or smaller than it, and after which all the elements are equal or greater. Note: Print -1, if no such element exists. Examples: Input: arr[] = [5, 1, 4, 3, 6, 8, 10, 7, 9]Output: 6 Explanation: 6 is present at index 4. All elements
      14 min read

    • Largest pair sum in an array
      Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum is 74. If there are less than 2 elements, then we need to return -1. Input : arr[] = {12, 34, 10, 6, 40}, Output : 74 Input : arr[] = {10, 10, 10}, Output : 20 Input arr[] = {10}, Output : -1 [
      10 min read

    • K’th Smallest Element in Unsorted Array
      Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content [Naive
      15+ min read

    • Search in a Sorted and Rotated Array
      Given a sorted and rotated array arr[] of n distinct elements, the task is to find the index of given key in the array. If the key is not present in the array, return -1. Examples: Input: arr[] = [5, 6, 7, 8, 9, 10, 1, 2, 3], key = 3Output: 8Explanation: 3 is present at index 8 in arr[]. Input: arr[
      15+ min read

    • Minimum in a Sorted and Rotated Array
      Given a sorted array of distinct elements arr[] of size n that is rotated at some unknown point, the task is to find the minimum element in it. Examples: Input: arr[] = [5, 6, 1, 2, 3, 4]Output: 1Explanation: 1 is the minimum element present in the array. Input: arr[] = [3, 1, 2]Output: 1Explanation
      9 min read

    • Find a Fixed Point (Value equal to index) in a given array
      Given an array of n distinct integers sorted in ascending order, the task is to find the First Fixed Point in the array. Fixed Point in an array is an index i such that arr[i] equals i. Note that integers in the array can be negative. Note: If no Fixed Point is present in the array, print -1. Exampl
      7 min read

    • K Mmost Frequent Words in a File
      Given a book of words and an integer K. Assume you have enough main memory to accommodate all words. Design a dynamic data structure to find the top K most frequent words in a book. The structure should allow new words to be added in main memory. Examples: Input: fileData = "Welcome to the world of
      15+ min read

    • Find k closest elements to a given value
      Given a sorted array arr[] and a value x, find the k closest elements to x in arr[]. Note that if the element is present in array, then it should not be in output, only the other closest elements are required. Examples: Input: k = 4, x = 35, arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 5
      15+ min read

    • 2 Sum - Pair Sum Closest to Target using Binary Search
      Given an array arr[] of n integers and an integer target, the task is to find a pair in arr[] such that it’s sum is closest to target. Note: Return the pair in sorted order and if there are multiple such pairs return the pair with maximum absolute difference. If no such pair exists return an empty a
      10 min read

    • Find the closest pair from two sorted arrays
      Given two arrays arr1[0...m-1] and arr2[0..n-1], and a number x, the task is to find the pair arr1[i] + arr2[j] such that absolute value of (arr1[i] + arr2[j] - x) is minimum. Example: Input: arr1[] = {1, 4, 5, 7}; arr2[] = {10, 20, 30, 40}; x = 32Output: 1 and 30Input: arr1[] = {1, 4, 5, 7}; arr2[]
      15+ min read

    • Find three closest elements from given three sorted arrays
      Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized. Here abs() indicates absolute value. Example : Input : A[] = {1, 4, 10} B[] = {2, 15, 20} C[] = {10, 12} Output: 10 15
      15+ min read

    • Search in an Array of Rational Numbers without floating point arithmetic
      Given a sorted array of rational numbers, where each rational number is represented in the form p/q (where p is the numerator and q is the denominator), the task is to find the index of a given rational number x in the array. If the number does not exist in the array, return -1. Examples: Input: arr
      9 min read

    Hard problems on Searching algorithms

    • Median of two sorted arrays of same size
      Given 2 sorted arrays a[] and b[], each of size n, the task is to find the median of the array obtained after merging a[] and b[]. Note: Since the size of the merged array will always be even, the median will be the average of the middle two numbers. Input: a[] = [1, 12, 15, 26, 38], b[] = [2, 13, 1
      15+ min read

    • Search in an almost sorted array
      Given a sorted integer array arr[] consisting of distinct elements, where some elements of the array are moved to either of the adjacent positions, i.e. arr[i] may be present at arr[i-1] or arr[i+1].Given an integer target. You have to return the index ( 0-based ) of the target in the array. If targ
      7 min read

    • Find position of an element in a sorted array of infinite numbers
      Given a sorted array arr[] of infinite numbers. The task is to search for an element k in the array. Examples: Input: arr[] = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170], k = 10Output: 4Explanation: 10 is at index 4 in array. Input: arr[] = [2, 5, 7, 9], k = 3Output: -1Explanation: 3 is not presen
      15+ min read

    • Pair Sum in a Sorted and Rotated Array
      Given an array arr[] of size n, which is sorted and then rotated around an unknown pivot, the task is to check whether there exists a pair of elements in the array whose sum is equal to a given target value. Examples : Input: arr[] = [11, 15, 6, 8, 9, 10], target = 16Output: trueExplanation: There i
      10 min read

    • K’th Smallest/Largest Element in Unsorted Array | Worst case Linear Time
      Given an array of distinct integers arr[] and an integer k. The task is to find the k-th smallest element in the array. For better understanding, k refers to the element that would appear in the k-th position if the array were sorted in ascending order. Note: k will always be less than the size of t
      15 min read

    • K'th largest element in a stream
      Given an input stream of n integers, represented as an array arr[], and an integer k. After each insertion of an element into the stream, you need to determine the kth largest element so far (considering all elements including duplicates). If k elements have not yet been inserted, return -1 for that
      15+ min read

    • Best First Search (Informed Search)
      Best First Search is a heuristic search algorithm that selects the most promising node for expansion based on an evaluation function. It prioritizes nodes in the search space using a heuristic to estimate their potential. By iteratively choosing the most promising node, it aims to efficiently naviga
      13 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences