BackhardBinary SearchGoogleNetflix

Segment Horizon Partition Engine 3 Solution

Problem Statement

You are given an integer matrix with n rows and m columns. Each row of the matrix is sorted in non‑decreasing order, but there is no relationship between different rows. For a given integer K (1 ≤ K ≤ n·m) you must determine the smallest integer X such that at least K elements of the matrix are less than or equal to X. In other words, X is the K‑th smallest value when all matrix elements are considered together. The answer must be found in O((n+m)·log V) time, where V is the range of values, by applying binary search on the answer space.

Input: The first line contains three space‑separated integers n, m and K. The next n lines each contain m space‑separated integers describing a row of the matrix; each row is guaranteed to be sorted in non‑decreasing order.

Output: Print a single integer X – the minimal value that satisfies the condition described above.

Example 1
Input
3 4 5 1 3 5 7 2 4 6 8 0 9 10 11
Output
4

Explanation: All 12 elements are: [0,1,2,3,4,5,6,7,8,9,10,11]. The 5‑th smallest element is 4, so the smallest X with at least 5 elements ≤ X is 4.

Example 2
Input
2 5 7 -5 -3 -1 0 2 -4 -2 1 3 5
Output
1

Explanation: Combined sorted list: [-5,-4,-3,-2,-1,0,1,2,3,5]. The 7‑th smallest element is 1. Any X < 1 would cover at most 6 elements, therefore the answer is 1.

Example 3
Input
4 3 10 10 20 30 5 15 25 1 2 3 8 12 16
Output
15

Explanation: All elements sorted: [1,2,3,5,8,10,12,15,16,20,25,30]. The 10‑th smallest value is 20, but we need the smallest X with ≥10 elements ≤ X. Since the 9‑th element is 16, X must be at least 20 to include the 10‑th element. Hence the answer is 20.

Constraints

  • 1 <= n, m <= 10^5
  • 1 <= n·m <= 10^6
  • -10^9 <= matrix[i][j] <= 10^9
  • Each row is sorted in non‑decreasing order
  • 1 <= K <= n·m
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Segment Horizon Partition Engine 3 — Problem Statement & Solution Guide

Binary SearchHardBinary Search on Answer Matrix
TimeO((log V)·n·log m)
|
SpaceO(1)

Problem Description

You are given an integer matrix with n rows and m columns. Each row of the matrix is sorted in non‑decreasing order, but there is no relationship between different rows. For a given integer K (1 ≤ K ≤ n·m) you must determine the smallest integer X such that at least K elements of the matrix are less than or equal to X. In other words, X is the K‑th smallest value when all matrix elements are considered together. The answer must be found in O((n+m)·log V) time, where V is the range of values, by applying binary search on the answer space.

Input: The first line contains three space‑separated integers n, m and K. The next n lines each contain m space‑separated integers describing a row of the matrix; each row is guaranteed to be sorted in non‑decreasing order.

Output: Print a single integer X – the minimal value that satisfies the condition described above.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Segment Horizon Partition Engine 3"

hard

WHY DOES IT MATTER?

The "search on answer" pattern turns a selection problem into a monotonic decision problem, enabling binary search over a numeric domain. It is essential when direct sorting is too costly, especially with large, partially ordered data structures.

OPTIMIZATION CHALLENGE

The key insight is that counting ≤ X can be done in logarithmic time per row because rows are sorted. Replacing a linear scan with binary search (or a two‑pointer walk) reduces the per‑iteration cost from O(m) to O(log m), which is the decisive factor for large matrices.

REAL-WORLD CONNECTION

Think of a distributed log system where each shard stores timestamps in order. To find the K‑th earliest event across shards, you don't gather all logs; instead you probe a timestamp and ask each shard how many events occurred before it, converging on the correct time via binary search.

During an interview, first articulate the monotonic predicate ("count ≤ X ≥ K") before jumping into code. Then write a helper that counts efficiently per row; this modularity prevents bugs and shows clean design.

COMPLEXITY AT A GLANCE

⏱ Time:O((log V)·n·log m)
💾 Space:O(1)

Core Theory — Why This Approach?

When each row of a matrix is sorted independently, the global ordering of all elements can be discovered without flattening the entire matrix. A naive scan would collect all n·m values, sort them, and pick the K‑th, which costs O(n·m log(n·m)) time and O(n·m) extra space—impractical for large matrices (e.g., n,m up to 10^5). The optimal paradigm leverages binary search on the value domain rather than on indices: we repeatedly guess a candidate value X and count how many matrix entries are ≤ X. Because each row is sorted, this count per row can be obtained in O(log m) via upper_bound, yielding O(n log m) per guess. The search space is bounded by the smallest and largest matrix entries, so the overall complexity becomes O((log MaxValue)·n·log m), which is dramatically faster and uses only O(1) auxiliary space. This technique—value‑based binary search combined with row‑wise binary searches—is a classic example of “search on answer” that transforms a combinatorial selection problem into a monotonic predicate evaluation.

Interview Questions on This Problem

Q1How would you find the K‑th smallest element in a row‑wise sorted matrix without using extra space?

Apply binary search on the value range: set low to the matrix's minimum and high to its maximum. For each mid, count elements ≤ mid by performing an upper_bound (or two‑pointer) scan on each row. If the count ≥ K, move high = mid; otherwise low = mid + 1. When low meets high, it is the K‑th smallest.

Q2What is the time complexity of the value‑based binary search solution and why does it outperform the flatten‑and‑sort method?

The solution runs in O((log V)·n·log m) time, where V is the value range (max‑min). Each iteration counts ≤ mid in O(n·log m) using binary search per row, and there are O(log V) iterations. This beats O(n·m log(n·m)) because it never materializes all elements and leverages the existing row order.

Q3Can you adapt the algorithm to work when both rows and columns are sorted? How does the complexity change?

If columns are also sorted, you can count ≤ mid in O(n + m) using a staircase walk from the bottom‑left corner, reducing the per‑iteration cost to O(n + m). The overall complexity becomes O((log V)·(n + m)), which is even faster for dense matrices.

Examples

Example 1

Input

3 4 5
1 3 5 7
2 4 6 8
0 9 10 11

Output

4

Explanation: All 12 elements are: [0,1,2,3,4,5,6,7,8,9,10,11]. The 5‑th smallest element is 4, so the smallest X with at least 5 elements ≤ X is 4.

Example 2

Input

2 5 7
-5 -3 -1 0 2
-4 -2 1 3 5

Output

1

Explanation: Combined sorted list: [-5,-4,-3,-2,-1,0,1,2,3,5]. The 7‑th smallest element is 1. Any X < 1 would cover at most 6 elements, therefore the answer is 1.

Example 3

Input

4 3 10
10 20 30
5 15 25
1 2 3
8 12 16

Output

15

Explanation: All elements sorted: [1,2,3,5,8,10,12,15,16,20,25,30]. The 10‑th smallest value is 20, but we need the smallest X with ≥10 elements ≤ X. Since the 9‑th element is 16, X must be at least 20 to include the 10‑th element. Hence the answer is 20.

Constraints

  • 1 <= n, m <= 10^5
  • 1 <= n·m <= 10^6
  • -10^9 <= matrix[i][j] <= 10^9
  • Each row is sorted in non‑decreasing order
  • 1 <= K <= n·m

Optimal Approach & Strategy

Binary search on the value range, counting ≤ mid in each row via upper_bound; adjust the range until low equals high, which is the K‑th smallest.

Brute Force Approach

Collect all n·m elements into a list, sort the list, and return the element at index K‑1.

Verified Code Solutions

JavaScript Solution
Time: O((log V)·n·log m)
function solution(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   return sum;
}

Asked in Top Tech Interviews

GoogleNetflix

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.