
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.
- The elements in the matrix are: [1,5,9,10,11,12,13,13,15].
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.
- The matrix contains only one element: -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)
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 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