Deepest Common Ancestors in a Multi-Parent DAG
Updated
Problem statement
The graph has nodes numbered from 0 through nodeCount - 1. Every pair [parent, child] in edges is a directed edge from an ancestor toward a descendant.
A node is an ancestor of itself. The depth of a node is the maximum number of edges on any path from a zero-indegree root to that node.
Return every node that is an ancestor of both first and second and has maximum depth among their common ancestors. Return the node IDs in ascending order. Return an empty array when there is no common ancestor.
Function
deepestCommonAncestors(nodeCount: int, edges: int[][], first: int, second: int) → int[]Examples
Example 1
nodeCount = 5edges = [[0,2],[1,2],[2,3],[2,4]]first = 3second = 4return = [2]Nodes 0, 1, and 2 are common ancestors. Node 2 has the greatest depth.
Example 2
nodeCount = 6edges = [[0,2],[1,3],[2,4],[3,4],[2,5],[3,5]]first = 4second = 5return = [2,3]Nodes 2 and 3 are incomparable common ancestors at the same maximum depth, so both are returned.
Constraints
1 <= nodeCount <= 100000.0 <= edges.length <= 200000.- Every edge contains two valid, distinct node IDs.
- The graph contains no directed cycle.
firstandsecondare valid node IDs.
More Salesforce Onsite Interview questions
- Count Increasing TripletsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Reverse a Sublist of a Linked ListONSITE INTERVIEW · Seen Nov 2026
- Rotting OrangesONSITE INTERVIEW · Seen Nov 2026
- 3Sum SmallerONSITE INTERVIEW · Seen Nov 2026
- Count Zero Request ServersONSITE INTERVIEW · Seen Nov 2026
- Group Identical Tree LevelsONSITE INTERVIEW · Seen Oct 2026
- Meeting Rooms IIONSITE INTERVIEW · Seen Oct 2026
- Construct a Tree from Level-Order and Inorder TraversalsONSITE INTERVIEW · Seen Sep 2026
- Maximize Monsters DefeatedONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- Course Order and CycleAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Course ScheduleOracle · ONSITE INTERVIEWOracle interview questions
- Package Install OrderVerily · ONSITE INTERVIEW
- Course SchedulePlaud · ONSITE INTERVIEW
- Course Schedule Cycle DetectionGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Audit Discounted Category AncestorsFaire · ONSITE INTERVIEW
- Detect a Cycle in a Directed GraphMakeMyTrip.com · ONSITE INTERVIEWMakeMyTrip.com interview questions
- Course ScheduleFlexTrade · ONSITE INTERVIEWFlexTrade interview questions
- Remove Redundant Task DependenciesMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Course ScheduleBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions