851. Loud and Rich
MediumView on LeetCode
Time: O(V+E)
Space: O(V)
Problem Overview
Loud and Rich (Medium) asks you to solve a structured algorithmic task. This is a common Array / Depth-First Search pattern in coding interviews. Build a richer-than graph; DFS with memoization propagates the quietest person reachable from each node.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Build a richer-than graph; DFS with memoization propagates the quietest person reachable from each node.
Related patterns: Array, Depth-First Search, Breadth-First Search
851.cs
C#
// Approach: Build a richer-than graph; DFS with memoization propagates the quietest person reachable from each node.
// Time: O(V+E) Space: O(V)
public class Solution
{
public int[] LoudAndRich(int[][] richer, int[] quiet)
{
int n = quiet.Length;
int[] ans = new int[n];
Array.Fill(ans, -1);
var graph = new List<int>[n];
for (int i = 0; i < n; i++)
graph[i] = new List<int>();
foreach (int[] r in richer)
{
int u = r[1];
int v = r[0];
graph[u].Add(v);
}
for (int i = 0; i < n; i++)
DFS(graph, i, quiet, ans);
return ans;
}
private int DFS(List<int>[] graph, int u, int[] quiet, int[] ans)
{
if (ans[u] != -1)
return ans[u];
ans[u] = u;
foreach (int v in graph[u])
{
int res = DFS(graph, v, quiet, ans);
if (quiet[res] < quiet[ans[u]])
ans[u] = res;
}
return ans[u];
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)