Bird
Raised Fist0
Interview Prepmodified-binary-searchmediumAmazonGoogleFacebook

Kth Smallest in Sorted Matrix

Choose your preparation mode4 modes available
📋
Problem

Imagine you have a large spreadsheet where each row and column is sorted, and you want to quickly find the kth smallest number without scanning the entire sheet.

Given an n x n matrix where each of the rows and columns is sorted in ascending order, find 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]]), k (int) Output: int (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 → smallest element in the matrixk = n*n → largest element in the matrixmatrix with all identical elements → kth smallest is that element
</>
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 smallest value due to counting elements < mid instead of <= midCount function excludes elements equal to mid, causing off-by-one errors.✅ Change count condition from 'element < mid' to 'element <= mid' in counting function.
Wrong: Output is the smallest or largest element regardless of kBinary search boundaries not updated correctly or count function always returns incorrect counts.✅ Ensure binary search low and high boundaries are initialized to matrix[0][0] and matrix[n-1][n-1], and count function returns accurate counts.
Wrong: Output is incorrect due to greedy approach picking elements row-wiseAlgorithm picks elements greedily without counting all elements <= mid properly.✅ Implement count function scanning from bottom-left or top-right to count elements <= mid correctly.
Wrong: Timeout or no output on large inputsUsing brute force approach sorting all elements instead of binary search on value range.✅ Implement binary search on value range with O(n) counting to reduce complexity from O(n^2 log n) to O(n log(max-min)).
✓
Test Cases
t1_01basic
Input{"matrix":[[1,5,9],[10,11,13],[12,13,15]],"k":8}
Expected13

The sorted order is [1,5,9,10,11,12,13,13,15], the 8th smallest is 13.

t1_02basic
Input{"matrix":[[1,2,3],[4,5,6],[7,8,9]],"k":5}
Expected5

Sorted order is [1,2,3,4,5,6,7,8,9], 5th smallest is 5.

t2_01edge
Input{"matrix":[[-5]],"k":1}
Expected-5

Single element matrix; kth=1 smallest is that element itself.

t2_02edge
Input{"matrix":[[2,2],[2,2]],"k":3}
Expected2

All elements identical; kth smallest is the identical element 2.

t2_03edge
Input{"matrix":[[-10,-5,0],[1,2,3],[4,5,6]],"k":1}
Expected-10

k=1 means smallest element, which is -10 here.

t3_01corner
Input{"matrix":[[1,3,5],[6,7,12],[11,14,14]],"k":6}
Expected11

Sorted order: [1,3,5,6,7,11,12,14,14], 6th smallest is 11.

t3_02corner
Input{"matrix":[[1,2,3],[4,5,6],[7,8,9]],"k":9}
Expected9

k=n*n=9 means largest element, which is 9.

t3_03corner
Input{"matrix":[[1,2,3],[2,3,4],[3,4,5]],"k":4}
Expected2

Sorted order: [1,2,2,3,3,3,4,4,5], 4th smallest is 2.

t4_01performance
Input{"_description":"n=300 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

n=300, O(n log(max-min)) binary search solution must complete within 2 seconds.

Practice

(1/5)
1. You are given a sorted array that has been rotated at an unknown pivot and may contain duplicates. You need to determine if a target value exists in this array efficiently. Which approach best guarantees an optimal average-case runtime while correctly handling duplicates?
easy
A. Use a simple linear scan through the array to find the target.
B. Apply a modified binary search that skips duplicates from both ends before deciding which half to search.
C. Use a classic binary search assuming no duplicates and no rotation.
D. Apply a dynamic programming approach to track possible target positions.

Solution

  1. Step 1: Understand problem constraints

    The array is rotated and contains duplicates, which breaks classic binary search assumptions.
  2. Step 2: Identify approach handling duplicates and rotation

    Modified binary search that skips duplicates at both ends before deciding the sorted half ensures correctness and efficiency.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Duplicates cause ambiguity; skipping them resolves it [OK]
Hint: Skip duplicates at boundaries before binary search [OK]
Common Mistakes:
  • Assuming classic binary search works with duplicates
  • Using DP unnecessarily
  • Relying on linear scan for efficiency
2. Consider the following Python code implementing an integer square root using Newton's method. What is the value of guess after the first iteration of the while loop when x = 8?
easy
A. 3
B. 4
C. 2
D. 1

Solution

  1. Step 1: Initialize variables for x=8

    Initial guess = 8 // 2 = 4.
  2. Step 2: First iteration update

    Check 4*4=16 > 8, so update guess = (4 + 8 // 4) // 2 = (4 + 2) // 2 = 3.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    First guess update correctly computes to 3 [OK]
Hint: Initial guess halves x; update uses integer division [OK]
Common Mistakes:
  • Off-by-one in guess update
  • Confusing integer division with float
  • Miscomputing initial guess
3. The following code attempts to find the k-th smallest number in an m x n multiplication table. Which line contains a subtle bug that can cause incorrect results for large inputs?
medium
A. Line 4: count = 0
B. Line 6: count += x // i # missing min with n
C. Line 8: if count >= k:
D. Line 13: mid = (low + high) // 2

Solution

  1. Step 1: Identify counting logic

    The counting function must cap counts per row by n, since each row has only n elements.
  2. Step 2: Analyze line 6

    Line 6 adds x // i without min(n, x // i), causing overcounting when x // i > n, leading to incorrect binary search decisions.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Bug causes wrong counts and incorrect final answer [OK]
Hint: Count per row capped by n to avoid overcounting [OK]
Common Mistakes:
  • Forgetting min(n, x//i) in counting
  • Incorrect mid calculation
4. What is the time complexity of the iterative fast exponentiation algorithm for computing x^n where n is a 32-bit integer?
medium
A. O(n)
B. O(n log n)
C. O(log n)
D. O(1)

Solution

  1. Step 1: Identify loop iterations

    The algorithm halves n each iteration, so the loop runs approximately log2(n) times.
  2. Step 2: Confirm work per iteration

    Each iteration does a constant number of multiplications and divisions, so total time is O(log n).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Halving exponent each step -> logarithmic time [OK]
Hint: Halving exponent means O(log n) time [OK]
Common Mistakes:
  • Confusing with O(n) from naive multiplication
  • Assuming O(1) due to constant ops per iteration
  • Thinking recursion adds extra complexity
5. Consider the following buggy code snippet for searching a target in a rotated sorted array with duplicates. Which line contains the subtle bug that can cause infinite loops or incorrect results?
medium
A. Line 9: if nums[mid] == target: return True
B. Line 7: mid = (left + right) // 2
C. Line 13: if nums[left] <= target < nums[mid]: right = mid - 1
D. Line 4: while left < right and nums[left] == nums[left + 1]: left += 1

Solution

  1. Step 1: Identify duplicate skipping logic

    The code only skips duplicates from the left side, ignoring duplicates on the right side.
  2. Step 2: Understand impact of skipping duplicates only on one side

    If duplicates exist on the right side, pointers may not move correctly, causing infinite loops or incorrect search decisions.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Skipping duplicates only on one side breaks correctness [OK]
Hint: Must skip duplicates from both ends to avoid infinite loops [OK]
Common Mistakes:
  • Skipping duplicates only from left or right
  • Not checking target at mid first
  • Incorrect pointer updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard