Ancestor and Descendant Counts in a DAG
Updated
Problem statement
You are given a directed acyclic graph with vertices 0 through n-1.
For every vertex, count its distinct ancestors and its distinct descendants. An ancestor reaches the vertex through one or more directed edges; a descendant is reachable from it through one or more edges.
Return an n x 2 matrix where row i is [ancestorCount, descendantCount]. Duplicate edges have no additional effect.
Function
countAncestorsAndDescendants(n: int, edges: int[][]) → int[][]Examples
Example 1
n = 4edges = [[0,1],[0,2],[1,3],[2,3]]return = [[0,3],[1,1],[1,1],[3,0]]Vertex 0 reaches all others; vertex 3 is reached by all earlier vertices.
Example 2
n = 3edges = []return = [[0,0],[0,0],[0,0]]An edgeless DAG has no nontrivial reachability.
Example 3
n = 3edges = [[0,1],[1,2],[0,2]]return = [[0,2],[1,1],[2,0]]Reachability is counted by distinct vertices, so the direct and indirect paths from 0 to 2 count once.
Constraints
1 <= n <= 500.0 <= edges.length <= 10000.- Every edge contains two distinct valid vertices and the graph is acyclic.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Longest Decreasing Matrix Path with Limited RelaxationsDuolingo · ONSITE INTERVIEWDuolingo interview questions
- Rocket Component CostSpaceX · ONSITE INTERVIEWSpaceX interview questions
- Distance Sums to Special Nodes in a Weighted TreeNutanix · ONSITE INTERVIEWNutanix interview questions
- Minimum Leaf Path Sum over All RootsInfosys · OAInfosys interview questions
- Process Graph Rule ValidationHadrian · PHONE SCREENHadrian interview questions
- Maximum Strength of Every NeuronMicrosoft · OAMicrosoft interview questions
- Best Currency Conversion PathSquarepoint Capital · PHONE SCREENSquarepoint Capital interview questions
- Tree Node With Maximum BeautyC3.ai · OAC3.ai interview questions
- All Halfway Courses Across Course TracksCrunchyroll · PHONE SCREENCrunchyroll interview questions
- Maximum Reservoir PowerWells Fargo · OAWells Fargo interview questions