Tutorialspoint
Problem
Solution
Submissions

Kth Smallest Element

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java program to find the kth smallest element in a n x n matrix where each row and column is sorted in ascending order. The matrix could be considered as n sorted arrays, and your task is to find the kth smallest element among all elements in the matrix.

Example 1
  • Input: matrix = [ [1, 5, 9], [10, 11, 13], [12, 13, 15] ] k = 8
  • Output: 13
  • Explanation: We need to find the 8th smallest element in the matrix. Listing all elements in sorted order: [1, 5, 9, 10, 11, 12, 13, 13, 15]. The 8th element is 13.
Example 2
  • Input: matrix = [ [1, 3, 5], [6, 7, 12], [11, 14, 20] ] k = 4
  • Output: 6
  • Explanation: We need to find the 4th smallest element in the matrix. Listing all elements in sorted order: [1, 3, 5, 6, 7, 11, 12, 14, 20]. The 4th element is 6.
Constraints
  • n == matrix.length
  • n == matrix[i].length
  • 1 ≤ n ≤ 300
  • -10^9 ≤ matrix[i][j] ≤ 10^9
  • All rows and columns are sorted in ascending order
  • 1 ≤ k ≤ n^2
  • Time Complexity: O(n * log(max-min))
  • Space Complexity: O(1)
MatrixGoogleGoldman Sachs
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

  • Consider using binary search to find the kth smallest element
  • Start the binary search with the smallest element (matrix[0][0]) and the largest element (matrix[n-1][n-1])
  • For each mid value in the binary search, count how many elements in the matrix are less than or equal to mid
  • If the count is less than k, search in the right half
  • If the count is greater than or equal to k, search in the left half and update the result
  • To count elements less than or equal to mid, use the property that rows and columns are sorted
  • Start from the bottom-left corner and move right if the current element is less than or equal to mid, otherwise move up

Steps to solve by this approach:

 Step 1: Initialize the binary search range with left = smallest element (matrix[0][0]) and right = largest element (matrix[n-1][n-1]).

 Step 2: While left < right, calculate mid and count how many elements in the matrix are less than or equal to mid.
 Step 3: If count < k, update left = mid + 1.
 Step 4: If count >= k, update right = mid.
 Step 5: To count elements, start from the bottom-left corner of the matrix.
 Step 6: Move right if the current element is less than or equal to the target, adding the number of elements in the current column that are less than or equal to target.
 Step 7: Move up if the current element is greater than the target.

Submitted Code :