Loud and Rich solution explained
Loud and Rich is solved by processing people from richest to poorest in topological order and passing each person's best answer down every "richer than" edge. Start with every person as their own answer; when you visit an edge from a richer person to a poorer one, the poorer person adopts the richer person's answer if it is quieter. Each person and each edge is handled once, so it runs in O(n + e) time.
By Evin JohnPublished 8 min read
The problem in plain words
There are n people numbered 0 to n - 1. You get a list of pairs [a, b], each meaning person a definitely has more money than person b. You also get an array quiet where quiet[i] is how quiet person i is; a smaller number means quieter, and all values are different. The money facts never contradict each other, so following "richer than" never loops back. For each person x, look at everyone who is certainly at least as rich as x, which is x plus anyone you can reach by repeatedly following "richer than" upward. Report the quietest of them. Return one answer per person.
| richer pairs | quiet | Answer | Why |
|---|---|---|---|
| [1,0], [2,1], [3,1] | [5, 2, 7, 1] | [3, 3, 2, 3] | Everyone is at least as rich as 0, and person 3 is quietest overall. Person 2 has nobody above them, so the answer for 2 is 2. |
| none | [0, 1, 2] | [0, 1, 2] | With no money facts, each person only knows about themselves. |
| [0,1], [1,2] | [3, 1, 2] | [0, 1, 1] | A chain. Person 2 can see 1 and 0 above, and 1 is quietest of those three. |
| [2,0], [2,1] | [4, 0, 9] | [0, 1, 2] | Person 2 is richer than both but loud, so 0 and 1 keep themselves. |
Two points to settle early. First, the comparison is "at least as rich", so each person is always a candidate for their own answer. Second, the answer is a person's index, not a quietness value. Mixing these up is the most common way to fail the first test case.
What this problem is really testing
The story is long, but the structure is a directed acyclic graph with one value per node, and a question that asks for the minimum over all ancestors of each node. Interviewers want to see you strip the story down to that sentence. Then the question becomes how to share work between people whose ancestor sets overlap. Candidates who see that the answer for x is just the best of x itself and the answers for x's direct richer neighbors have found the recurrence, and both clean solutions follow from it.
Slow approach: search upward from each person
Build a map from each person to the people directly richer than them. For each x, run a BFS through that map, collecting every ancestor. Track the quietest person seen, starting with x. Each search touches up to n people and e edges, and you run n searches, so the cost is O(n · (n + e)). With a few hundred people that is fine; with tens of thousands of people and edges it is not.
from collections import deque
def quietest_above_slow(n, richer, quiet):
above = [[] for _ in range(n)]
for a, b in richer:
above[b].append(a)
result = []
for x in range(n):
best = x
seen = {x}
queue = deque([x])
while queue:
person = queue.popleft()
if quiet[person] < quiet[best]:
best = person
for r in above[person]:
if r not in seen:
seen.add(r)
queue.append(r)
result.append(best)
return resultMain approach: carry the answer down in topological order
Flip the direction. Draw edges from richer to poorer. Give every person a starting answer of themselves. If you process people so that everyone richer than x is finished before x, then x only needs to look at its direct richer neighbors: their answers already summarize everyone above them. Kahn's algorithm gives exactly that order. Count how many richer neighbors each person has. Start the queue with people who have none. When you pop person a, walk each edge a to b: if the answer for a is quieter than the current answer for b, b takes it. Then lower b's count and push b when the count reaches zero.
from collections import deque
def quietest_above(n, richer, quiet):
poorer = [[] for _ in range(n)]
waiting = [0] * n
for a, b in richer:
poorer[a].append(b)
waiting[b] += 1
answer = list(range(n))
queue = deque(i for i in range(n) if waiting[i] == 0)
while queue:
a = queue.popleft()
for b in poorer[a]:
if quiet[answer[a]] < quiet[answer[b]]:
answer[b] = answer[a]
waiting[b] -= 1
if waiting[b] == 0:
queue.append(b)
return answerfunction quietestAbove(n, richer, quiet) {
const poorer = Array.from({ length: n }, () => []);
const waiting = new Array(n).fill(0);
for (const [a, b] of richer) {
poorer[a].push(b);
waiting[b]++;
}
const answer = Array.from({ length: n }, (_, i) => i);
const queue = [];
for (let i = 0; i < n; i++) if (waiting[i] === 0) queue.push(i);
for (let head = 0; head < queue.length; head++) {
const a = queue[head];
for (const b of poorer[a]) {
if (quiet[answer[a]] < quiet[answer[b]]) answer[b] = answer[a];
if (--waiting[b] === 0) queue.push(b);
}
}
return answer;
}The memoized DFS version
The same recurrence can be computed top-down: best(x) is the quietest among x and best(r) for each r directly richer than x, with results cached. It is shorter to write and is what many people reach for first. In Python, a chain of several thousand people will exceed the default recursion limit, so either raise it with a comment explaining why, or prefer the queue version, which has no depth at all.
Tracing the first example
- Edges and countsRicher to poorer: 1 to 0, 2 to 1, 3 to 1. Counts: person 0 has 1, person 1 has 2, persons 2 and 3 have 0.
- Pop 2Edge 2 to 1: quiet of 2 is 7, quiet of 1 is 2, so 1 keeps itself. Person 1's count drops to 1.
- Pop 3Edge 3 to 1: quiet of 3 is 1, quieter than 2, so the answer for 1 becomes 3. The count reaches 0 and 1 is pushed.
- Pop 1, then 0Edge 1 to 0: the answer for 1 is 3 with quiet 1, quieter than 5, so 0 also takes 3. Final: [3, 3, 2, 3].
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Upward BFS per person | O(n · (n + e)) | O(n + e) |
| Kahn's order, push answers down | O(n + e) | O(n + e) |
| Memoized DFS upward | O(n + e) | O(n + e) plus recursion depth |
Edge cases to test
- No richer pairs at all: the answer is [0, 1, ..., n - 1].
- One person who is richer than everyone and also the quietest: every answer is that person.
- A rich person who is louder than everyone below them: nobody adopts them.
- Two richer neighbors with different answers: the poorer person must end up with the quieter one regardless of the order edges are processed.
- A long chain, which breaks naive recursion in Python.
- A repeated pair [a, b] in the input: the count for b goes up twice and goes down twice, so the queue version still works.
Mistakes that cost points
- Returning quietness values instead of person indexes.
- Comparing quiet[a] with quiet[b] instead of quiet[answer[a]] with quiet[answer[b]]. The candidate passed down is the best person above a, not a itself.
- Leaving each person out of their own candidate set, which breaks the case where x is quieter than everyone richer.
- Pointing the edges the wrong way and computing the quietest poorer person instead.
- Processing people in index order instead of topological order, so a person is finalized before everyone richer has been seen.
Talking through it
Fictional example
- Candidate
- Underneath the story, this is a DAG where edges go from richer to poorer, and for each node I want the quietest node among itself and all its ancestors.
- Candidate
- If I visit nodes in topological order, every ancestor of x is finished before x, so x only needs its direct richer neighbors' answers. I will start everyone with themselves and pass the quieter answer down each edge.
- Candidate
- Kahn's algorithm gives the order and touches each edge once, so it is O(n + e). I chose the queue over recursion because a long chain could hit Python's stack limit.
Related walkthroughs
Find All Possible Recipes uses the same in-degree counting to decide what can be built, without carrying a value along. Course Schedule IV asks about ancestors too, but needs a yes or no for arbitrary pairs instead of a single best per node. For the dynamic programming side of this recurrence, see the algorithm interview questions guide.
Natively for practice
When you work through DAG problems on your own, Natively can read the prompt from a screenshot and offer a direction, which you can weigh against your recurrence once you have written it down. It keeps a local transcript of a spoken practice round, so you can see whether you stated the reduction to ancestors before diving into code. More on an AI interview assistant for Mac and Windows.
Questions people ask
What is the efficient solution to Loud and Rich?
Process people in topological order from richest to poorest. Each person starts as their own answer, and along each edge from richer to poorer the poorer person adopts the richer person's answer if it is quieter. That is O(n + e).
Is Loud and Rich a DFS or a topological sort problem?
Either works. A memoized DFS computes the quietest ancestor top-down, and Kahn's algorithm computes it bottom-up. The queue version avoids recursion limits on long chains.
Why compare quiet[answer[a]] and not quiet[a]?
The value passed down an edge is the best person found anywhere above a, which may be someone richer than a. Comparing only a itself loses those people.
Does each person count as a candidate for their own answer?
Yes. The question asks about everyone at least as rich as x, which includes x, so every answer starts as the person themselves.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
