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 loudness. You are given an array richer
where richer[i] = [ai, bi]
indicates that person ai
has more money than person bi
and an integer array quiet
where quiet[i]
is the quietness of the i
-th person. All the arrays are 0-indexed.
Return an integer array answer
where answer[x] = y
indicates that the person y
that the person x
would choose to be the quietest among all people who definitely have equal to or more money than person x
.
n
and the size of the richer
array?ricker
array is empty?n
?a
to node b
indicates that a
has more money than b
.def loudAndRich(richer, quiet):
n = len(quiet)
# Build the adjacency list for the graph
graph = [[] for _ in range(n)]
for u, v in richer:
graph[v].append(u)
# Result array and memoization
answer = [-1] * n
def dfs(node):
# If answer[node] has already been computed, return it.
if answer[node] != -1:
return answer[node]
# Start with the assumption that the node itself is the quietest
answer[node] = node
for neighbor in graph[node]:
candidate = dfs(neighbor)
if quiet[candidate] < quiet[answer[node]]:
answer[node] = candidate
return answer[node]
# Compute for each person
for i in range(n):
dfs(i)
return answer
O(E)
, where E
is the number of edges in the richer
array.O(V + E)
, where V
is the number of nodes and E
is the number of edges.O(V + E)
, which is efficient for typical constraints on such problems.This approach efficiently computes the required answers and leverages memoization to avoid redundant calculations, making it optimal for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?