Tutorialspoint
Problem
Solution
Submissions

Kth Smallest Element in a Sorted Matrix

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the kth smallest element in an n x n matrix where each of the rows and columns are sorted in ascending order. The matrix elements are sorted both row-wise and column-wise.

Example 1
  • Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
  • Output: 13
  • Explanation:
    • The elements in the matrix are: [1,5,9,10,11,12,13,13,15].
    • When sorted: [1,5,9,10,11,12,13,13,15].
    • The 8th smallest element (1-indexed) is 13.
Example 2
  • Input: matrix = [[-5]], k = 1
  • Output: -5
  • Explanation:
    • The matrix contains only one element: -5.
    • The 1st smallest element is -5.
    • Therefore, the answer is -5.
Constraints
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order
  • 1 <= k <= n^2
  • Time Complexity: O(n * log(max - min))
  • Space Complexity: O(1)
AlgorithmsMatrixAirbnbArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use binary search on the range of values in the matrix
  • The smallest value is matrix[0][0] and largest is matrix[n-1][n-1]
  • For each mid value, count how many elements are <= mid
  • Count elements efficiently by starting from top-right or bottom-left corner
  • If count >= k, search in lower half; otherwise search in upper half
  • Use the property that rows and columns are sorted

Steps to solve by this approach:

 Step 1: Initialize left pointer to matrix[0][0] (smallest element) and right pointer to matrix[n-1][n-1] (largest element)
 Step 2: Use binary search on the value range, calculate mid = left + (right - left) / 2
 Step 3: Count how many elements in matrix are <= mid using efficient counting from bottom-left corner
 Step 4: If count < k, the kth element is larger, so move left = mid + 1
 Step 5: If count >= k, the kth element is <= mid, so move right = mid
 Step 6: Continue until left == right, which gives us the kth smallest element
 Step 7: Return the final value as the kth smallest element

Submitted Code :