惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
The Blog of Author Tim Ferriss
博客园 - 司徒正美
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
有赞技术团队
有赞技术团队
量子位
S
SegmentFault 最新的问题
博客园 - 聂微东
博客园 - 【当耐特】
J
Java Code Geeks
美团技术团队
Hugging Face - Blog
Hugging Face - Blog
H
Help Net Security
V
V2EX
人人都是产品经理
人人都是产品经理
博客园 - Franky
罗磊的独立博客
Engineering at Meta
Engineering at Meta
A
About on SuperTechFans
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
Y
Y Combinator Blog
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Median in a Row Wise Sorted Matrix | Binary Search on Answer
Jaspreet singh · 2026-06-21 · via DEV Community

Jaspreet singh

Problem Statement

Given a row-wise sorted matrix of size N × M, find the median of the matrix.

The matrix contains an odd number of elements.


Brute Force Intuition

In an interview, you can explain it like this:

Since every row is sorted, one straightforward approach is to collect all elements into a single array, sort them, and return the middle element. This works but ignores the fact that rows are already sorted.

Complexity

  • Time Complexity: O(N × M × log(N × M))
  • Space Complexity: O(N × M)

Brute Force Code

class Solution {

    public int median(int[][] mat) {

        List<Integer> list = new ArrayList<>();

        for (int[] row : mat) {

            for (int num : row) {
                list.add(num);
            }
        }

        Collections.sort(list);

        return list.get(list.size() / 2);
    }
}


Moving Towards the Optimal Approach

Notice that we don't actually need the sorted array.

We only need:

How many numbers are smaller than or equal to X?

If we can answer this efficiently, we can binary search the median value.


Pattern Recognition

Whenever you see:

  • Sorted Rows
  • Find kth smallest / median
  • Value range known

Think:

Binary Search on Answer


Key Observation

Suppose:

mid = 10

Count:

How many elements ≤ 10 ?

If that count is:

Too small

Median lies on the right.

If count is:

Large enough

Median lies on the left.


Why Upper Bound?

Each row is sorted.

For every row we can find:

Count of elements ≤ mid

using Binary Search.

This takes:

O(log M)

per row.


Optimal Java Solution

class Solution {

    public int median(int[][] mat) {

        int n = mat.length;
        int m = mat[0].length;

        int low = 1;
        int high = 2000;

        int required = (n * m) / 2;

        while (low <= high) {

            int mid = low + (high - low) / 2;

            int count = 0;

            for (int[] row : mat) {
                count += upperBound(row, mid);
            }

            if (count <= required) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return low;
    }

    private int upperBound(int[] row, int target) {

        int low = 0;
        int high = row.length - 1;

        while (low <= high) {

            int mid = low + (high - low) / 2;

            if (row[mid] <= target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return low;
    }
}


Dry Run

Input

1  3  5
2  6  9
3  6  9

Total Elements:

9

Median Position:

9 / 2 = 4

Need the 5th smallest element.


Iteration 1

mid = 5

Count elements ≤ 5:

Row1 → 3
Row2 → 1
Row3 → 1

Total = 5

Since:

5 > 4

Move Left.


Iteration 2

mid = 3

Count elements ≤ 3:

Row1 → 2
Row2 → 1
Row3 → 1

Total = 4

Since:

4 <= 4

Move Right.


Result

Median = 5


Why Binary Search Works?

We are not searching indices.

We are searching values.

For every value:

Count(elements ≤ value)

This count grows monotonically.

Hence Binary Search becomes possible.


Complexity Analysis

Metric Complexity
Time Complexity O(log(MaxValue) × N × log M)
Space Complexity O(1)

Where:

  • log(MaxValue) → Binary Search on answer.
  • log(M) → Upper Bound in each row.

Interview One-Liner

Binary search the value range and count how many elements are ≤ mid using upper bound on every sorted row.


Pattern Learned

Sorted Structure
+
Need kth Smallest / Median
+
Monotonic Count

=> Binary Search on Answer

Similar Problems

  • Median in Matrix
  • Kth Smallest Element in Matrix
  • Aggressive Cows
  • Koko Eating Bananas
  • Nth Root of Number
  • Capacity to Ship Packages

Memory Trick

Think:

Guess a Number (mid)

Count:
How many elements ≤ mid ?

Count Too Small
→ Move Right

Count Large Enough
→ Move Left

Mental Model

Binary Search on Index
→ Search Position

Binary Search on Answer
→ Search Value

Whenever you hear:

"Median in Sorted Matrix"

your brain should immediately think:

Count Elements ≤ Mid + Binary Search on Answer