Topological Sort || Kahn's Algorithm|| Java 
Complexity
Time complexity: O(E+V+E2logV)

For building graph - O(E)
For populating indegree - O(E)
For BFS - O(V+E)
For Ancestors - O(V2)
For Sorting - O(V2log
# Complexity
- Time complexity: $$O(E+V+E^2logV)$$
  - For building graph - $$O(E)$$
  - For populating indegree - $$O(E)$$
  - For BFS - $$O(V+E)$$
  - For Ancestors - $$O(V^2)$$
  - For Sorting - $$O(V^2logV)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:$$O(V^2)$$  
  - For Adjacency list - $$O(V+E)$$
  - For Indegree Array - $$O(V)$$
  - For Ancestor List -$$O(V^2)$$
  - For Queue - $$O(V)$$
  - For Final Result - $$O(V^2)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class Solution {
    public List<List<Integer>> getAncestors(int n, int[][] edges) {
        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
        for(int i=0;i<n;i++){
            adj.add(new ArrayList<>());
        }
         for (int[] edge : edges) {
            adj.get(edge[0]).add(edge[1]);
        }
        int indegree[] = new int[n];
        for (int[] edge:edges) {
            indegree[edge[1]]++;
        }
        List<Set<Integer>> res = new ArrayList<>();
        for(int i=0;i<n;i++){
            res.add(new HashSet<>());
        }
        Queue<Integer> q = new LinkedList<Integer>();
        for(int i=0;i<n;i++){
            if(indegree[i]==0)q.add(i);
        }
        
        while(!q.isEmpty()){
            int k= q.poll();
            for(int child : adj.get(k)){
                res.get(child).addAll(res.get(k));
                res.get(child).add(k);
                indegree[child]--;
                if(indegree[child]==0){
                    q.add(child);
                }
            }
        }
        List<List<Integer>> ans = new ArrayList<>();
        for (Set<Integer> hs : res) {
            List<Integer> ls = new ArrayList<>(hs);
            Collections.sort(ls); 
            ans.add(ls);
        }
        return ans;
    }
}

['Breadth-First Search', 'Graph', 'Topological Sort', 'Java']