Imagine you have a large spreadsheet where each row is sorted, and you want to quickly find the kth smallest number without flattening the entire sheet.
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Input: matrix (List[List[int]]), integer k
Output: integer representing the kth smallest element
n == matrix.length == matrix[i].length1 ≤ n ≤ 300-10^9 ≤ matrix[i][j] ≤ 10^91 ≤ k ≤ n^2
Edge cases: k = 1 → returns smallest element in matrixk = n*n → returns largest element in matrixmatrix with duplicate elements → kth smallest counts duplicates
</>
IDE
def kthSmallest(matrix: list[list[int]], k: int) -> int:public int kthSmallest(int[][] matrix, int k)int kthSmallest(vector<vector<int>>& matrix, int k)function kthSmallest(matrix, k)
def kthSmallest(matrix, k):
# Write your solution here
pass
class Solution {
public int kthSmallest(int[][] matrix, int k) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int kthSmallest(vector<vector<int>>& matrix, int k) {
// Write your solution here
return 0;
}
function kthSmallest(matrix, k) {
// Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Wrong kth element due to off-by-one indexingUsing zero-based indexing incorrectly when k is 1-based✅ Adjust indexing by accessing k-1 element or popping heap k times
Wrong: Incorrect element due to greedy selection from rowsSelecting smallest elements from each row independently without global ordering✅ Use min-heap to merge rows or binary search counting instead of greedy
Wrong: Wrong count in binary search with negative numbersNot setting binary search low and high to matrix min and max values✅ Initialize low = matrix[0][0], high = matrix[n-1][n-1] and count elements <= mid correctly
Wrong: Wrong kth element when duplicates presentSkipping duplicates or miscounting elements in heap or binary search✅ Count duplicates properly and do not skip equal elements
Wrong: Timeout on large inputUsing brute force flatten and sort approach✅ Implement binary search on value range or min-heap merge approach
✓
Test Cases
Focus on handling smallest and largest k values and matrices with duplicates.
Watch out for common pitfalls like greedy selection and off-by-one errors.
Optimize your solution to avoid brute force and pass large input tests.
Sorted elements: [-10,-5,0,1,2,3,4,5,6], 4th smallest is 1.
💡 Check if algorithm handles negative numbers correctly in binary search.
💡 Ensure counting elements <= mid works with negative values.
💡 Adjust binary search range to include negative minimum.
Why it failed: Fails with negative numbers due to incorrect range or count; fix by setting low and high to matrix min and max.
✓ Correctly handles negative and positive values in binary search.
t4_01performance
Input{"_description":"n=300 at constraint boundary - executor generates this input"}
Expectednull
⏱ Performance - must finish in 2000ms
n=300, O(n log(max-min)) binary search or O(k log n) heap approach must complete within 2 seconds.
💡 Brute force O(n^2 log n^2) will time out for n=300.
💡 Use binary search on value range or min-heap merge for efficiency.
💡 Avoid flattening entire matrix or naive sorting.
Why it failed: TLE due to brute force or inefficient approach; fix by implementing binary search or min-heap merge.
✓ Efficient algorithm runs within time limit.
Practice
(1/5)
1. You are given an unsorted array and need to find the element that ranks kth when the array is sorted in descending order. Which algorithmic approach is best suited to find this element efficiently without fully sorting the array?
easy
A. Sort the entire array and pick the kth element from the end.
B. Use a greedy algorithm that picks the largest elements one by one until kth is reached.
C. Use a dynamic programming approach to build solutions for smaller subproblems.
D. Use a partition-based selection algorithm that partially sorts the array around a pivot.
Solution
Step 1: Understand problem requirements
The problem asks for the kth largest element without fully sorting the array, so a full sort is not optimal.
Step 2: Identify suitable algorithm
Partition-based selection (Quickselect) partially sorts the array around pivots, achieving average O(n) time, which is more efficient than sorting.
Final Answer:
Option D -> Option D
Quick Check:
Partial sorting via partitioning -> efficient selection [OK]
Hint: Partial sorting via partitioning is faster than full sorting [OK]
Common Mistakes:
Assuming full sort is always needed
Confusing greedy with selection
Thinking DP applies here
2. Consider the following buggy Quickselect implementation. Which line contains the subtle bug that can cause incorrect results?
medium
A. Line 4: The comparison operator in the if condition inside partition
B. Line 7: The swap of nums[i] and nums[right]
C. Line 11: The base case check if left == right
D. Line 15: The recursive call when pivot_index < k
Solution
Step 1: Identify partition logic
Partition should move elements greater than pivot to the left for kth largest.
Step 2: Locate bug
The condition uses '<' instead of '>', reversing the order and breaking correctness.
Final Answer:
Option A -> Option A
Quick Check:
Incorrect comparison flips partition logic [OK]
Hint: Partition comparison must match desired order (greater for kth largest) [OK]
Common Mistakes:
Using wrong comparison direction in partition
Confusing base case with recursion
Swapping wrong elements
3. The following code attempts to implement the optimal bucket sort approach for top k frequent elements. Identify the line that contains a subtle bug that can cause incorrect results or runtime errors.
medium
A. Line updating frequency dictionary with freq.get(num, 0) + 1
B. Line iterating over freq.items() to append elements to buckets
C. Line creating buckets with size max_freq instead of max_freq + 1
D. Line iterating buckets from max_freq - 1 down to 0
Solution
Step 1: Check bucket list size
Buckets are created with size max_freq, but frequencies range from 1 to max_freq inclusive, so index max_freq is needed.
Step 2: Consequence of incorrect bucket size
Accessing buckets[count] where count == max_freq causes IndexError or missing elements if bucket list is too small.
Final Answer:
Option C -> Option C
Quick Check:
Bucket list must have max_freq + 1 slots to index frequencies correctly [OK]
Hint: Bucket size must be max_freq + 1 to include max frequency [OK]
Common Mistakes:
Off-by-one bucket size
Misindexing buckets causing runtime errors
4. Suppose you want to find the kth largest element in an array where elements can be repeated and you want to find the kth largest unique element instead. Which modification to the Quickselect approach is correct?
hard
A. Use a min-heap of size k to store unique elements only, ignoring duplicates during insertion.
B. Run Quickselect as usual and then scan left and right to skip duplicates until kth unique is found.
C. Sort the array fully and iterate from largest to smallest counting unique elements until kth unique is reached.
D. Modify partition to skip duplicates and recurse only on unique elements.
Solution
Step 1: Understand uniqueness constraint
Quickselect partitions by value but does not handle uniqueness inherently.
Step 2: Evaluate modifications
Partial scanning or modifying partition is complex and error-prone; min-heap requires extra checks.
Step 3: Choose reliable approach
Sorting fully and counting unique elements is straightforward and guarantees correctness.
Final Answer:
Option C -> Option C
Quick Check:
Full sort enables unique counting easily [OK]
Hint: Uniqueness requires full sort or extra data structures [OK]
Common Mistakes:
Assuming Quickselect handles uniqueness
Trying to modify partition without correctness
Ignoring duplicates in heap approach
5. Suppose you want to find the top k frequent words but now words can be reused infinitely many times (like unlimited supply). Which modification to the optimal bucket sort approach correctly handles this scenario?
hard
A. This problem reduces to a knapsack variant; bucket sort no longer applies
B. Modify frequency counting to consider infinite reuse, then apply bucket sort as usual
C. Use a dynamic programming approach to count combinations of words for frequencies
D. Use a max heap keyed by frequency and word lex order, repeatedly pop top k elements
Solution
Step 1: Understand infinite reuse impact
Infinite reuse means frequency counts are not fixed; problem becomes combinatorial.
Step 2: Recognize problem class change
Top k frequent words with unlimited reuse resembles knapsack or coin change, not simple frequency counting.
Step 3: Bucket sort no longer applies
Bucket sort relies on fixed frequencies; dynamic programming or other combinatorial methods are needed.
Final Answer:
Option A -> Option A
Quick Check:
Infinite reuse breaks frequency counting assumptions [OK]
Hint: Infinite reuse changes problem class, bucket sort invalid [OK]
Common Mistakes:
Trying to reuse bucket sort with infinite counts
Ignoring combinatorial explosion
Assuming heap approach suffices
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.