#851

Loud and Rich

Medium
ArrayDepth-First SearchGraph TheoryTopological SortHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + e)
Space
O(1)
O(n)
💡

Intuition

Time O(n + e)Space O(n)

The optimal approach uses a graph representation of the relationships and a depth-first search (DFS) to propagate the quietness information. This allows us to efficiently find the quietest person among those who are richer.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a graph where each person points to those they are richer than.
  2. 2Step 2: Use DFS to explore each person, keeping track of the quietest person found in the path.
  3. 3Step 3: Store results in the answer array, ensuring that we only update if we find a quieter person.
solution.py19 lines
1def loudAndRich(richer, quiet):
2    from collections import defaultdict
3    n = len(quiet)
4    graph = defaultdict(list)
5    for a, b in richer:
6        graph[a].append(b)
7    answer = [-1] * n
8    def dfs(person):
9        if answer[person] != -1:
10            return answer[person]
11        answer[person] = person
12        for richer_person in graph[person]:
13            candidate = dfs(richer_person)
14            if quiet[candidate] < quiet[answer[person]]:
15                answer[person] = candidate
16        return answer[person]
17    for i in range(n):
18        dfs(i)
19    return answer

Complexity note: The time complexity is O(n + e), where n is the number of people and e is the number of richer relationships. This is efficient because we only visit each person and each relationship once. The space complexity is O(n) for storing the graph and the answer array.

  • 1Understanding the relationship between quietness and wealth is crucial.
  • 2Graph traversal techniques like DFS can simplify complex relationships.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.