<p>You are given a positive integer <code>n</code> representing the number of nodes of a <strong>Directed Acyclic Graph</strong> (DAG). The nodes are numbered from <code>0</code> to <code>n - 1</code> (<strong>inclusive</strong>).</p>

<p>You are also given a 2D integer array <code>edges</code>, where <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> denotes that there is a <strong>unidirectional</strong> edge from <code>from<sub>i</sub></code> to <code>to<sub>i</sub></code> in the graph.</p>

<p>Return <em>a list</em> <code>answer</code><em>, where </em><code>answer[i]</code><em> is the <strong>list of ancestors</strong> of the</em> <code>i<sup>th</sup></code> <em>node, sorted in <strong>ascending order</strong></em>.</p>

<p>A node <code>u</code> is an <strong>ancestor</strong> of another node <code>v</code> if <code>u</code> can reach <code>v</code> via a set of edges.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2019/12/12/e1.png" style="width: 322px; height: 265px;" />
<pre>
<strong>Input:</strong> n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
<strong>Output:</strong> [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
<strong>Explanation:</strong>
The above diagram represents the input graph.
- Nodes 0, 1, and 2 do not have any ancestors.
- Node 3 has two ancestors 0 and 1.
- Node 4 has two ancestors 0 and 2.
- Node 5 has three ancestors 0, 1, and 3.
- Node 6 has five ancestors 0, 1, 2, 3, and 4.
- Node 7 has four ancestors 0, 1, 2, and 3.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2019/12/12/e2.png" style="width: 343px; height: 299px;" />
<pre>
<strong>Input:</strong> n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
<strong>Output:</strong> [[],[0],[0,1],[0,1,2],[0,1,2,3]]
<strong>Explanation:</strong>
The above diagram represents the input graph.
- Node 0 does not have any ancestor.
- Node 1 has one ancestor 0.
- Node 2 has two ancestors 0 and 1.
- Node 3 has three ancestors 0, 1, and 2.
- Node 4 has four ancestors 0, 1, 2, and 3.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 1000</code></li>
	<li><code>0 &lt;= edges.length &lt;= min(2000, n * (n - 1) / 2)</code></li>
	<li><code>edges[i].length == 2</code></li>
	<li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub> &lt;= n - 1</code></li>
	<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>
	<li>There are no duplicate edges.</li>
	<li>The graph is <strong>directed</strong> and <strong>acyclic</strong>.</li>
</ul>

class Solution:
    def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
       #Note: we want all ancestors of all nodes 
       #Topological sort will give us the ordering but doesn't confirm direct relation
       #Could just do DFS forest 
        #parent->child, parent stores child, child returns all it's children and 
        #parent can also store those --> list combining is O(n) tho 
        #We would then have to sort all those lists
        
        #ANCESTOR IS PARENT NOT CHILD
        #Issue with DFS is that we need to
        #SIMPLE: reverse the edges 

    #     adjacency_list = [[] for _ in range(n)]
    #     ancestors = [[] for _ in range(n)]

    #     # Populate the adjacency list with edges
    #     for from_node, to_node in edges:
    #         adjacency_list[from_node].append(to_node)

    #     # Perform DFS for each node to find all its ancestors
    #     for i in range(n):
    #         self.find_ancestors_DFS(i, adjacency_list, i, ancestors)

    #     return ancestors

    # # Helper method to perform DFS and find ancestors
    # def find_ancestors_DFS(
    #     self, ancestor, adjacency_list, current_node, ancestors
    # ):
    #     for child_node in adjacency_list[current_node]:
    #         # Check if the ancestor is already added to avoid duplicates
    #         if (
    #             not ancestors[child_node]
    #             or ancestors[child_node][-1] != ancestor
    #         ):
    #             ancestors[child_node].append(ancestor)
    #             self.find_ancestors_DFS(
    #                 ancestor, adjacency_list, child_node, ancestors
    #             )

        #O(n^2 log n) worst case, O(n^2) memoery
        adj = {}
        for parent, child in edges:
            if child not in adj:
                adj[child] = []
            adj[child].append(parent)

        #mapping child to parent 
        #Can simply return nodes upwards 
        
        #O(n)
        answer = []
        for _ in range(n): #can also use this as a seen map ? 
            answer.append([])
        seen = [False] * n  # To track nodes whose ancestors have been fully computed

        def dfs(node):
            if seen[node]:
                return answer[node]
            
            # If the node has no parents, it has no ancestors
            if node not in adj:
                seen[node] = True
                return []
            
            ancestors = []
            for parent in adj[node]:
                # Recursively find the ancestors of the parent
                parent_ancestors = dfs(parent)
                
                # Add the parent itself if not already in the ancestors list
                if parent not in ancestors:
                    ancestors.append(parent)
                
                # Add all ancestors of the parent, avoiding duplicates
                for ancestor in parent_ancestors:
                    if ancestor not in ancestors:
                        ancestors.append(ancestor)
            
            # Mark the node as fully processed
            seen[node] = True
            answer[node] = ancestors
            return ancestors

        for node in range(n):
            dfs(node)
        for node in range(n): #O(n) per node worst case
            answer[node] = sorted((answer[node])) #
        return answer
        
            
1775