Leetcode 2192: All Ancestors of a Node in a Directed Acyclic Graph

grid47
grid47
Exploring patterns and algorithms
Apr 1, 2024 7 min read

You are given a directed acyclic graph (DAG) with n nodes, numbered from 0 to n-1. Along with this, you are given a list of directed edges where each edge [fromi, toi] indicates a directed edge from node fromi to node toi. For each node in the graph, you need to determine the list of all its ancestors. A node u is an ancestor of node v if there is a path from u to v through one or more directed edges. Return a list answer where answer[i] contains the sorted list of ancestors of the i-th node.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n` representing the number of nodes in the graph, followed by a list of edges describing the directed edges.
Example: n = 6, edgeList = [[0,1],[0,2],[1,3],[1,4],[2,5],[4,5]]
Constraints:
• 1 <= n <= 1000
• 0 <= edges.length <= min(2000, n * (n - 1) / 2)
• edges[i].length == 2
• 0 <= fromi, toi <= n - 1
• fromi != toi
• There are no duplicate edges
• The graph is directed and acyclic
Output: Return a list `answer` where `answer[i]` is the list of ancestors of the `i`-th node, sorted in ascending order.
Example: [[], [0], [0], [0, 1], [0, 1, 2], [0, 1, 2, 4]]
Constraints:
• The list of ancestors for each node should be sorted in ascending order.
Goal: The goal is to compute the ancestors of each node in the graph efficiently.
Steps:
• 1. Create a graph representation using adjacency lists for outgoing edges and maintain a count of incoming edges for each node.
• 2. Perform a topological sort using Kahn's algorithm to ensure that nodes are processed in the correct order.
• 3. For each node, use its ancestors (processed nodes) and propagate the ancestors through the graph, adding them to the current node's ancestor set.
Goal: The solution should handle up to 1000 nodes and up to 2000 edges efficiently.
Steps:
• 1 <= n <= 1000
• edges.length <= 2000
Assumptions:
• The graph is acyclic, so there will be no cycles.
Input: n = 6, edgeList = [[0,1],[0,2],[1,3],[1,4],[2,5],[4,5]]
Explanation: In this case, node 0 has no ancestors, node 1 has node 0 as an ancestor, node 3 has nodes 0 and 1 as ancestors, and so on.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus