Loud and Rich — LeetCode 851 Python Solution

MediumDepth-First SearchGraphTopological SortArray
Problem
#851
Reading time
4 min

The problem

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] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person.

Example

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]
Explanation
answer[0] = 5.

Python solution

Python
class Solution:
    def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
        def dfs(i: int):
            if ans[i] != -1:
                return
            ans[i] = i
            for j in g[i]:
                dfs(j)
                if quiet[ans[j]] < quiet[ans[i]]:
                    ans[i] = ans[j]

        g = defaultdict(list)
        for a, b in richer:
            g[b].append(a)
        n = len(quiet)
        ans = [-1] * n
        for i in range(n):
            dfs(i)
        return ans

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Topological Sort

Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 851. Loud and Rich is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.

The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 851. Loud and Rich?
LeetCode 851. Loud and Rich is rated Medium on LeetCode.
What is the time complexity of LeetCode 851. Loud and Rich?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 851. Loud and Rich?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 851. Loud and Rich cover?
LeetCode 851. Loud and Rich is tagged Depth-First Search, Graph, Topological Sort and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview