Tutorialspoint
Problem
Solution
Submissions

Kth Smallest Element

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 row and column is sorted in ascending order.

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].
    • The 8th smallest number is 13.
Example 2
  • Input: matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], k = 5
  • Output: 5
  • Explanation:
    • The elements in the matrix are [1, 2, 3, 4, 5, ...].
    • The 5th smallest number is 5.
Constraints
  • n == matrix.length
  • n == matrix[i].length
  • 1 ≤ n ≤ 300
  • -10^9 ≤ matrix[i][j] ≤ 10^9
  • All rows and columns in the matrix are sorted in ascending order
  • 1 ≤ k ≤ n^2
  • Time Complexity: O(n * log(max-min))
  • Space Complexity: O(1)
ArraysAlgorithmsDeloitteSamsung
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 to find the kth smallest element
  • For each mid value, count how many elements are less than or equal to it
  • Utilize the sorted property of rows and columns to efficiently count
  • You can also consider using a priority queue (min-heap) approach
  • Be careful about duplicate elements in the matrix

Steps to solve by this approach:

 Step 1: Set the search range for binary search - start with the smallest element (top-left) and end with the largest element (bottom-right).
 Step 2: For each mid value in the binary search, count how many elements in the matrix are less than or equal to it.
 Step 3: To count efficiently, start from the bottom-left corner and move either right or up.
 Step 4: If the current count is less than k, move the left boundary up; otherwise, move the right boundary down.
 Step 5: Continue the binary search until left meets right.
 Step 6: The final value of left is the kth smallest element.
 Step 7: Be careful with duplicate values in the matrix - this approach handles them correctly.

Submitted Code :