KatInterview

881. Loud and Rich

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine, for each person x, the quietest person y from the set of all people who are at least as rich as x. The "richer than" relationships can be modeled as a directed graph.

Solution

Loud and Rich in Python

class Solution:
    def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
        n = len(quiet)
        # adj[i] contains a list of people richer than i.
        adj = [[] for _ in range(n)]
        for u, v in richer:
            # If person u is richer than v, we add an edge from v to u.
            # This way, we can traverse from a person to all people richer than them.
            adj[v].append(u)

        # answer[i] stores the quietest person at least as rich as i.
        # We initialize with -1 to indicate not computed.
        answer = [-1] * n

        def dfs(node):
            # If the answer for this node is already computed (memoized), return it.
            if answer[node] != -1:
                return answer[node]
            
            # Initially, the quietest person is the node itself.
            answer[node] = node

            # Explore all people richer than the current node.
            for richer_node in adj[node]:
                # Recursively find the quietest person for the richer_node's group.
                candidate = dfs(richer_node)
                
                # If the candidate from the richer group is quieter, update.
                if quiet[candidate] < quiet[answer[node]]:
                    answer[node] = candidate
            
            return answer[node]

        # Run DFS for each person.
        for i in range(n):
            if answer[i] == -1:
                dfs(i)
        
        return answer

Loud and Rich in Java

class Solution {
    private List<List<Integer>> adj;
    private int[] quiet;
    private int[] answer;

    public int[] loudAndRich(int[][] richer, int[] quiet) {
        int n = quiet.length;
        this.adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<>());
        }

        // Build the graph where an edge from u to v means v is richer than u.
        for (int[] r : richer) {
            adj.get(r[1]).add(r[0]);
        }

        this.quiet = quiet;
        this.answer = new int[n];
        // Initialize answer array with -1 to mark as not computed.
        Arrays.fill(answer, -1);

        // Run DFS for each person.
        for (int i = 0; i < n; i++) {
            if (answer[i] == -1) {
                dfs(i);
            }
        }

        return answer;
    }

    private int dfs(int node) {
        // If the answer for this node is already computed (memoized), return it.
        if (answer[node] != -1) {
            return answer[node];
        }

        // Initially, the quietest person is the node itself.
        answer[node] = node;

        // Explore all people richer than the current node.
        for (int richerNode : adj.get(node)) {
            // Get the quietest person for the richerNode's group through recursion.
            int candidate = dfs(richerNode);

            // If the candidate from the richer group is quieter than our current best, update.
            if (quiet[candidate] < quiet[answer[node]]) {
                answer[node] = candidate;
            }
        }

        // Return the final answer for this node, which is now memoized.
        return answer[node];
    }
}

Loud and Rich in C++

class Solution {
public:
    vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
        int n = quiet.size();
        // adj[i] contains a list of people richer than i.
        vector<vector<int>> adj(n);
        for (const auto& r : richer) {
            // If person r[0] is richer than r[1], we add an edge from r[1] to r[0].
            // This way, we can traverse from a person to all people richer than them.
            adj[r[1]].push_back(r[0]);
        }

        // answer[i] stores the quietest person at least as rich as i.
        // We initialize with -1 to indicate that the result for a person is not yet computed.
        vector<int> answer(n, -1);

        // We run DFS for each person to find their answer.
        for (int i = 0; i < n; ++i) {
            if (answer[i] == -1) {
                dfs(i, adj, quiet, answer);
            }
        }

        return answer;
    }

private:
    // DFS to find the quietest person for a given node.
    void dfs(int node, const vector<vector<int>>& adj, const vector<int>& quiet, vector<int>& answer) {
        // If the answer for this node is already computed, we don't need to do anything.
        // This check is for the main loop, but in the recursion it's handled by the return value.
        // To be more precise, we can say the result is memoized, so we return.
        if (answer[node] != -1) {
            return;
        }

        // Initially, the quietest person is the node itself.
        answer[node] = node;

        // Explore all people who are richer than the current node.
        for (int richer_node : adj[node]) {
            // Recursively find the answer for the richer_node.
            dfs(richer_node, adj, quiet, answer);
            
            // Compare the quietness. If the quietest person for the `richer_node` group
            // is quieter than the current quietest person for our `node` group, we update.
            if (quiet[answer[richer_node]] < quiet[answer[node]]) {
                answer[node] = answer[richer_node];
            }
        }
    }
};

Loud and Rich in TypeScript

function loudAndRich(richer: number[][], quiet: number[]): number[] {
    const n = quiet.length;
    // adj[i] contains a list of people richer than i.
    const adj: number[][] = Array(n).fill(0).map(() => []);
    for (const [u, v] of richer) {
        // If person u is richer than v, we add an edge from v to u.
        // This allows traversal from a person to all those richer than them.
        adj[v].push(u);
    }

    // answer[i] stores the quietest person at least as rich as i.
    // Initialize with -1 to indicate not computed.
    const answer: number[] = new Array(n).fill(-1);

    const dfs = (node: number): number => {
        // If the answer for this node is already computed (memoized), return it.
        if (answer[node] !== -1) {
            return answer[node];
        }

        // Initially, the quietest person is the node itself.
        answer[node] = node;

        // Explore all people richer than the current node.
        for (const richerNode of adj[node]) {
            // Recursively find the quietest person for the richerNode's group.
            const candidate = dfs(richerNode);

            // If the candidate from the richer group is quieter, update.
            if (quiet[candidate] < quiet[answer[node]]) {
                answer[node] = candidate;
            }
        }

        return answer[node];
    };

    // Run DFS for each person.
    for (let i = 0; i < n; i++) {
        if (answer[i] === -1) {
            dfs(i);
        }
    }

    return answer;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.