Loud and Rich

DFS with memo — for each person, the answer is the minimum-quietness among self and all richer-than-self (transitively).

Medium
Time O(n + e) Space O(n + e)
LeetCode
4 min read
graph dfs memo topological-sort

Problem#

richer[i] = [a, b] means person a is richer than person b. For each x, return the index of the quietest person among those at least as rich as x (including x).

Examples#

  • richer=[[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3],[7,0]], quiet=[3,2,5,4,6,1,7,0][5,5,2,5,4,5,6,7].

Constraints#

  • 1 <= n <= 500.

Approach#

Build a DAG: edge a → b iff a is richer than b. For each x, DFS over all reachable from x (richer-than-x) and pick the one with the smallest quiet. Memoize.

Solution#

Loud and Rich
class Solution {
vector<vector<int>> adj;
vector<int> quiet;
vector<int> ans;
int dfs(int x) {
if (ans[x] != -1) return ans[x];
ans[x] = x;
for (int y : adj[x]) {
int c = dfs(y);
if (quiet[c] < quiet[ans[x]]) ans[x] = c;
}
return ans[x];
}
public:
vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& q) {
int n = q.size();
quiet = q;
adj.assign(n, {});
ans.assign(n, -1);
for (auto& r : richer) adj[r[1]].push_back(r[0]);
for (int i = 0; i < n; ++i) dfs(i);
return ans;
}
};

Editorial#

Direction matters: edges point “less rich → more rich” so DFS from x enumerates all richer people. Memoization makes the whole sweep linear in nodes plus edges; the DAG structure (richness is a partial order) guarantees no cycles.

Complexity#

  • Time: O(n + e).
  • Space: O(n + e).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.