There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.

You are given an array richer where richer[i] = [a_i, b_i] indicates that a_i has more money than b_i, and an integer array quiet where quiet[i] is the quietness of the i-th person.

All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time).

Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.

Input & Output

Example 1 — Basic Wealth Hierarchy
$ Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
Output: [5,5,2,5,4,5,6,7]
💡 Note: For person 0: People with ≥ money are {0,1,2,3,4,5,6}, quietest is 5 (quiet=1). For person 1: People with ≥ money are {1,2,3,4,5,6}, quietest is 5 (quiet=1).
Example 2 — Simple Chain
$ Input: richer = [[1,0]], quiet = [1,0]
Output: [1,1]
💡 Note: Person 1 is richer than person 0. For person 0: can reach {0,1}, quietest is 1. For person 1: can only reach {1}, so answer is 1.
Example 3 — No Relationships
$ Input: richer = [], quiet = [0]
Output: [0]
💡 Note: Only one person with no wealth relationships, so each person's quietest reachable person is themselves.

Constraints

  • 1 ≤ n ≤ 500
  • 0 ≤ richer.length ≤ n * (n-1) / 2
  • 0 ≤ ai, bi < n
  • ai != bi
  • All pairs (ai, bi) are distinct
  • The observations in richer are all logically consistent

Visualization

Tap to expand
Loud and Rich: Find Quietest Reachable PersonInput: richer=[[1,0]], quiet=[3,2]01quiet=3quiet=2Person 1 is richer than Person 0For person 0: reachable = {0,1}quietest is 1 (quiet=2 < quiet=3)answer[0] = 1For person 1: reachable = {1}answer[1] = 1Output: [1, 1]Each person finds the quietest among all people with ≥ wealth
Understanding the Visualization
1
Input
Wealth relationships and quietness values
2
Process
Build graph and find quietest reachable for each person
3
Output
Array where answer[i] is quietest person reachable from person i
Key Takeaway
🎯 Key Insight: Model as directed graph and use DFS with memoization to efficiently find quietest reachable person for each node
Asked in
Google 12 Facebook 8 Amazon 6
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen