LeetCode 2192: All Ancestors of a Node in a Directed Acyclic Graph Solution
Master LeetCode problem 2192 (All Ancestors of a Node in a Directed Acyclic Graph), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2192. All Ancestors of a Node in a Directed Acyclic Graph
Problem Explanation
Explanation
To find all ancestors of a node in a Directed Acyclic Graph (DAG), we can perform a depth-first search (DFS) starting from each node and keeping track of the ancestors for each node. We can use a hashmap to store the ancestors for each node.
- Create an adjacency list representation of the graph using the edges provided.
- Initialize a hashmap to store the ancestors for each node.
- Perform a DFS from each node to find its ancestors.
- During the DFS, update the ancestors hashmap for each node visited.
- Return the list of ancestors for each node in the desired format.
Time complexity: O(V + E), where V is the number of vertices and E is the number of edges. Space complexity: O(V + E) for the adjacency list and hashmap.
Solution Code
class Solution {
public List<List<Integer>> allAncestors(int n, int[][] edges) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
}
List<List<Integer>> ancestors = new ArrayList<>();
for (int i = 0; i < n; i++) {
Set<Integer> visited = new HashSet<>();
List<Integer> currentAncestors = new ArrayList<>();
dfs(i, graph, visited, currentAncestors);
ancestors.add(currentAncestors);
}
return ancestors;
}
private void dfs(int node, List<List<Integer>> graph, Set<Integer> visited, List<Integer> currentAncestors) {
if (visited.contains(node)) {
return;
}
visited.add(node);
for (int parent : graph.get(node)) {
currentAncestors.add(parent);
dfs(parent, graph, visited, currentAncestors);
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2192 (All Ancestors of a Node in a Directed Acyclic Graph)?
This page provides optimized solutions for LeetCode problem 2192 (All Ancestors of a Node in a Directed Acyclic Graph) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2192 (All Ancestors of a Node in a Directed Acyclic Graph)?
The time complexity for LeetCode 2192 (All Ancestors of a Node in a Directed Acyclic Graph) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2192 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2192 in Java, C++, or Python.