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 will be given two lists: richer
and quiet
.
richer[i] = [a, b]
means a person a
is richer than a person b
.quiet[i]
is the loudness of the i-th
person: the larger the value, the quieter the person is.Return an integer array answer
where answer[i] = x
means that person x
is the quietest person (i.e. has the most amount of money) among all people who are richer than or equal to i
.
quiet
list can have multiple people with the same quietness value.richer
list or the quiet
array?
a
to b
indicates a
is richer than b
.import java.util.*;
public class Solution {
public int[] loudAndRich(int[][] richer, int[] quiet) {
int n = quiet.length;
List<Integer>[] graph = new List[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int[] pair : richer) {
graph[pair[1]].add(pair[0]);
}
int[] answer = new int[n];
Arrays.fill(answer, -1);
for (int i = 0; i < n; i++) {
dfs(i, graph, quiet, answer);
}
return answer;
}
private int dfs(int node, List<Integer>[] graph, int[] quiet, int[] answer) {
if (answer[node] != -1) {
return answer[node];
}
answer[node] = node;
for (int neighbor : graph[node]) {
int cand = dfs(neighbor, graph, quiet, answer);
if (quiet[cand] < quiet[answer[node]]) {
answer[node] = cand;
}
}
return answer[node];
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] richer = // use example above
int[] quiet = {2, 3, 1, 0};
System.out.println(Arrays.toString(sol.loudAndRich(richer, quiet))); // Output: [0, 1, 1, 3]
}
}
O(E)
where E
is the number of edges in the richer
relationships.O(V + E)
time complexity, where V
is the number of vertices (people).Thus, the overall time complexity remains O(V + E)
. This is efficient given the problem constraints.
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?