1. In-Degree and Out-Degree Matrix Scan
Intuition
A celebrity has outDegree == 0 (knows nobody) and inDegree == N - 1 (known by all). Count degrees for everyone and check.
Algorithm
- Step 1: Initialize
inDegreeandoutDegreearrays of sizeN. - Step 2: Loop
ifrom 0 toN - 1andjfrom 0 toN - 1. - Step 3: If
M[i][j] == 1, incrementoutDegree[i]++andinDegree[j]++. - Step 4: Find any person
kwithoutDegree[k] == 0andinDegree[k] == N - 1. - Step 5: Return
kif found, else-1.
#include <iostream>#include <vector> class Solution {public: int celebrity(std::vector<std::vector<int>>& M) { int n = M.size(); std::vector<int> inDegree(n, 0), outDegree(n, 0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (M[i][j] == 1) { outDegree[i]++; inDegree[j]++; } } } for (int i = 0; i < n; i++) { if (inDegree[i] == n - 1 && outDegree[i] == 0) { return i; } } return -1; }}; int main() { Solution solver; std::vector<std::vector<int>> M = { {0, 1, 0}, {0, 0, 0}, {0, 1, 0} }; std::cout << "Celebrity: " << solver.celebrity(M) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Count in-degrees and out-degrees by iterating through all N x N cells of the matrix. - Space complexity:
O(N)— O(N) arrays for indegree and outdegree counts.
Why Brute Force Doesn't Scale:
For N = 3,000, N2 = 9,000,000 cell reads.
Two Pointers makes at most 9,000 matrix reads (~3N), 1,000x faster.