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

推荐订阅源

V
Visual Studio Blog
N
Netflix TechBlog - Medium
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
T
Tailwind CSS Blog
IT之家
IT之家
博客园 - Franky
雷峰网
雷峰网
博客园 - 聂微东
腾讯CDC
M
MIT News - Artificial intelligence
B
Blog RSS Feed
博客园_首页
罗磊的独立博客
S
SegmentFault 最新的问题
I
InfoQ
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
D
Docker
宝玉的分享
宝玉的分享
B
Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

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
Celebrity Problem
Jaspreet singh · 2026-06-29 · via DEV Community

Jaspreet singh

Problem Statement

A celebrity is a person who:

  • Knows no one.
  • Is known by everyone else.

Given an N × N matrix:

M[i][j] = 1

→ i knows j

Find the celebrity.

Return:

Celebrity Index

OR

-1

if no celebrity exists.


Brute Force Intuition

In an interview, you can explain it like this:

Check every person individually. Verify whether they know nobody and everybody else knows them.

This requires checking an entire row and column for every person.

Complexity

  • Time Complexity: O(N²)
  • Space Complexity: O(1)

Brute Force Code

class Solution {

    public int celebrity(int[][] M, int n) {

        for (int i = 0; i < n; i++) {

            boolean celebrity = true;

            for (int j = 0; j < n; j++) {

                if (i == j)
                    continue;

                if (M[i][j] == 1 ||
                    M[j][i] == 0) {

                    celebrity = false;
                    break;
                }
            }

            if (celebrity)
                return i;
        }

        return -1;
    }
}


Moving Towards the Optimal Approach

Notice an important observation.

Suppose:

A knows B

Then:

A

Cannot be Celebrity

Similarly,

If:

A does NOT know B

Then:

B

Cannot be Celebrity

So with one comparison,

we eliminate one candidate.


Pattern Recognition

Whenever you see:

  • Eliminate Candidates
  • Pairwise Comparison
  • Find One Possible Answer

Think:

Two Pointers / Elimination


Key Observation

Start with:

Person 0

Person N-1

Compare:

Does Left Know Right ?

YES

Left Cannot Be Celebrity

Move Left++


NO

Right Cannot Be Celebrity

Move Right--

Eventually,

only one candidate survives.

Now simply verify.


Optimal Approach

Step 1

Keep:

left = 0

right = n-1


Step 2

If:

M[left][right] == 1

Move:

left++

Else:

right--


Step 3

One candidate remains.

Verify:

  • Entire Row
  • Entire Column

Optimal Java Solution

class Solution {

    public int celebrity(int[][] M, int n) {

        int left = 0;
        int right = n - 1;

        while (left < right) {

            if (M[left][right] == 1) {

                left++;

            } else {

                right--;
            }
        }

        int candidate = left;

        for (int i = 0; i < n; i++) {

            if (i == candidate)
                continue;

            if (M[candidate][i] == 1 ||
                M[i][candidate] == 0) {

                return -1;
            }
        }

        return candidate;
    }
}


Dry Run

Input

      0 1 2

0 → [0 1 1]

1 → [0 0 1]

2 → [0 0 0]


Step 1

Left = 0

Right = 2

Check:

0 knows 2

YES

Move:

Left = 1


Step 2

Check:

1 knows 2

YES

Move:

Left = 2

Candidate:

2


Verification

Row:

0 0 0

Knows nobody ✓

Column:

1

1

0

Everyone knows 2 ✓

Answer:

2


Why Two Pointers Work?

Every comparison removes exactly one person from consideration.

After:

N-1 comparisons

only one possible celebrity remains.

The final verification confirms whether that candidate satisfies the celebrity conditions.


Complexity Analysis

Metric Complexity
Time Complexity O(N)
Space Complexity O(1)

Interview One-Liner

Eliminate one candidate in every comparison using two pointers, then verify the remaining candidate by checking its row and column.


Pattern Learned

Pairwise Elimination

↓

One Candidate Left

↓

Verify Candidate

Similar Problems

  • Celebrity Problem
  • Find the Judge (LeetCode)
  • Gas Station
  • Majority Element
  • Boyer-Moore Voting Algorithm

Memory Trick

Think:

A Knows B ?

↓

Yes

↓

A Cannot Be Celebrity

-------------------

No

↓

B Cannot Be Celebrity

Mental Model

Compare Two People

↓

Eliminate One

↓

Repeat

↓

One Candidate Left

↓

Verify

Whenever you hear:

"Find the celebrity"

your brain should immediately think:

Candidate Elimination + Verification