bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 851. Loud and Rich

851. Loud and Rich

Leetcode Solutions

Cached Depth-First Search

  1. Initialize an adjacency list to represent the graph based on the richer array.
  2. Initialize an array answer with the same length as quiet and fill it with -1, indicating that we have not computed the answer for that person yet.
  3. For each person i, if answer[i] is -1, call the dfs function on that person.
  4. Implement the dfs function that takes a person x and returns the quietest person in the subtree rooted at x.
  5. If answer[x] is not -1, return answer[x] as it has already been computed.
  6. Otherwise, set answer[x] to x initially, and for each child y of x in the graph, update answer[x] to the quieter person between answer[x] and dfs(y).
  7. Return answer[x].
  8. After processing all people, return the answer array.
UML Thumbnail

Breadth-First Search with Sorting

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...