Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Binary Search

Median of a Row-Wise Sorted Matrix

Hard · Binary Search · Asked at Amazon, Microsoft, Directi

Every row of the R × C matrix is sorted in non-decreasing order, and R × C is odd. Print the median of all the elements.

Input

First line: R C. Next R lines: C integers each.

Output

The median.

Constraints

Binary search on the value v between the smallest and largest element. Count elements ≤ v with one upper-bound binary search per row: O(R log C). The median is the smallest v with count > R × C / 2. Total O(R log C log 10^9) — no need to merge or sort everything.

Example 1

Input

3 3
1 3 5
2 6 9
3 6 9

Output

5

Example 2

Input

1 1
7

Output

7

Hints

  1. The median is the smallest value v such that more than half of the elements are ≤ v.
  2. Counting elements ≤ v is easy row by row: one upper-bound binary search per row.
  3. Binary search v itself between the smallest and the largest element.

Approach

Let half = R·C / 2 (integer division). lo = minimum of the first column, hi = maximum of the last column. For mid, count = Σ over rows of upper_bound(row, mid). If count ≤ half, the median is larger (lo = mid + 1); otherwise hi = mid. The loop ends on an actual element — the median — without ever merging the rows.

Complexity: O(R · log C · log(max value)) time · O(R · C) space for the input

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int R, C;
    cin >> R >> C;
    vector<vector<long long>> g(R, vector<long long>(C));
    for (auto &row : g)
        for (auto &x : row) cin >> x;
    long long lo = LLONG_MAX, hi = LLONG_MIN;
    for (auto &row : g) {
        lo = min(lo, row[0]);
        hi = max(hi, row[C - 1]);
    }
    long long half = (long long) R * C / 2;
    while (lo < hi) {
        long long mid = lo + (hi - lo) / 2, cnt = 0;
        for (auto &row : g) cnt += upper_bound(row.begin(), row.end(), mid) - row.begin();
        if (cnt <= half) lo = mid + 1;
        else hi = mid;
    }
    cout << lo << "\n";
    return 0;
}

Python solution

import sys
from bisect import bisect_right

data = list(map(int, sys.stdin.read().split()))
R, C = data[0], data[1]
g = [data[2 + i * C : 2 + (i + 1) * C] for i in range(R)]
lo = min(row[0] for row in g)
hi = max(row[-1] for row in g)
half = R * C // 2
while lo < hi:
    mid = (lo + hi) // 2
    cnt = sum(bisect_right(row, mid) for row in g)
    if cnt <= half:
        lo = mid + 1
    else:
        hi = mid
print(lo)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int R = (int) in.nval;
        in.nextToken();
        int C = (int) in.nval;
        long[][] g = new long[R][C];
        long lo = Long.MAX_VALUE, hi = Long.MIN_VALUE;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                in.nextToken();
                g[i][j] = (long) in.nval;
            }
            lo = Math.min(lo, g[i][0]);
            hi = Math.max(hi, g[i][C - 1]);
        }
        long half = (long) R * C / 2;
        while (lo < hi) {
            long mid = lo + (hi - lo) / 2, cnt = 0;
            for (long[] row : g) {
                int a = 0, b = C;
                while (a < b) {
                    int m = (a + b) / 2;
                    if (row[m] <= mid) a = m + 1;
                    else b = m;
                }
                cnt += a;
            }
            if (cnt <= half) lo = mid + 1;
            else hi = mid;
        }
        System.out.println(lo);
    }
}

Solve Median of a Row-Wise Sorted Matrix online · All practice problems