
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)
Editorial
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. |
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