Skip to content

Commit 358eac1

Browse files
Add new solution with explanation
1 parent e192080 commit 358eac1

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Intuition
2+
The intuition behind the approach is to use a DFS to traverse the graph and find the ancestors of each node. By starting the DFS from each node and adding the current node to the ans list of its children, we ensure that all the ancestors of a node are recorded in the ans list of that node.
3+
The directChild list is used to keep track of the direct children of each node, which helps in efficiently traversing the graph during the DFS.
4+
5+
Approach
6+
The approach used in the code is a depth-first search (DFS) to find the ancestors of each node in the graph represented by the given edges.
7+
8+
Initialize two lists: ans to store the ancestors of each node, and directChild(dc) to store the direct children of each node.
9+
Iterate through the edges list and add each child node to the directChild(dc) list of its parent node.
10+
Iterate through the nodes from 0 to n-1 and perform a DFS starting from each node.
11+
In the DFS function, for each child node of the current node, check if the current node is not already present in the ans list of the child node. If not, add the current node to the ans list of the child node and recursively call the DFS function with the child node as the new current node.
12+
Return the ans list as the final result.
13+
Complexity
14+
Time complexity:O(n + m)
15+
Space complexity:O(n + m)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) {
9+
vector<vector<int>> ans(n), directChild(n);
10+
for (auto& e : edges) {
11+
directChild[e[0]].push_back(e[1]);
12+
}
13+
for (int i = 0; i < n; i++) {
14+
dfs(i, i, ans, directChild);
15+
}
16+
return ans;
17+
}
18+
19+
private:
20+
void dfs(int x, int curr, vector<vector<int>>& ans, vector<vector<int>>& directChild) {
21+
for (int ch : directChild[curr]) {
22+
if (ans[ch].empty() || ans[ch].back() != x) {
23+
ans[ch].push_back(x);
24+
dfs(x, ch, ans, directChild);
25+
}
26+
}
27+
}
28+
};

0 commit comments

Comments
 (0)