Skip to main content

Find Final Destination

easy
Software engineer

Given a list of directed edges representing one-way connections between nodes in a graph, and a starting node start. Each edge is given as a two-element array [u, v] where u is the source node and v is the target node.

Your task is to find the destination node (a node without outgoing edges) by traveling from the starting node along these directed edges until you reach the destination.

Note that the graph might have multiple disconnected components, but it is guaranteed that for the given input, there is a unique destination reachable from start and no cycles exist in the graph.

Example 1

Input

edges = [["B","C"], ["D","B"], ["C","A"], ["E","F"]], start = "D"

Output

"A"

Explanation

Beginning at node 'D', we look for an edge starting with 'D'. We find ['D', 'B'], so we move to 'B'. From 'B', we follow ['B', 'C'] to 'C'. From 'C', we follow ['C', 'A'] to 'A'. Since there are no edges starting with 'A', 'A' is the final destination.

Example 2

Input

edges = [["A","B"], ["B","C"], ["C","D"], ["D","E"], ["E","F"], ["F","G"]], start = "A"

Output

"G"

Example 3

Input

edges = [["A","D"], ["B","D"], ["C","D"], ["D","E"], ["F","G"], ["G","E"]], start = "F"

Output

"E"

Constraints

  • All nodes are represented by unique strings.
  • The graph is acyclic.
  • There is exactly one unique destination reachable from the given starting node.
  • 1 <= edges.length <= 10⁴

ScreeningOnsite

ArrayGraph TheoryHash TableSimulation
Language
Code editor loads in the browser.

Output

Input

[["B","C"],["D","B"],["C","A"],["E","F"]]
"D"

Expected

"A"

Your output

Run to see your output.