KatInterview

Locate the Junction of Two Chains in a Successor Table

Linked ListsAuto-graded · 23 test cases
MediumAuto-gradedLinked Listslinked-listhash-settwo-pointers

Last updated

Find the first node of one chain that also lies on a second chain, where both chains are encoded in a single successor array, or report -1 if they never converge.

You are given a collection of n nodes labeled 0 to n - 1. Their connections are stored in a single array successor, where successor[i] is the label of the node that comes right after node i, or -1 if node i has no following node (it is the end of its chain).

Two chains are described by their starting nodes, start_a and start_b. A chain is the sequence of nodes you visit by beginning at its start node and repeatedly moving to successor[current] until you reach -1.

The two chains may converge: from some node onward they can share all remaining nodes. Your task is to find the junction.

Return the label of the first node of chain A that also appears in chain B. If the chains have no node in common, return -1.

Rules

  • Nodes are identified by label. A node is shared only if it is the very same node (same label) in both chains.
  • Every node has exactly one successor, so once the chains share a node they share everything after it. The first shared node along chain A is therefore also the first shared node along chain B, and the answer is unique.
  • If start_a == start_b, the chains are identical and the answer is start_a.
  • One chain may begin inside the other; in that case the answer is the start of the chain whose start lies on the other chain.

Function

Implement find_junction(successor, start_a, start_b) that returns the junction label as an integer, or -1 if there is none.

Constraints

  • 1 <= n <= 100000, where n = len(successor)
  • -1 <= successor[i] <= n - 1 and successor[i] != i
  • 0 <= start_a <= n - 1 and 0 <= start_b <= n - 1
  • Following successor from start_a or from start_b reaches -1 without visiting any node twice (no cycles).
  • Every node belongs to chain A, chain B, or both.

Examples

Example 1

Input: find_junction([1, 2, 3, -1, 5, 2], 0, 4)

Output: 2

Example 2

Input: find_junction([1, -1, 3, -1], 0, 2)

Output: -1

Example 3

Input: find_junction([1, 2, -1], 1, 0)

Output: 1

Hints

Hint 1

Think of the question as membership: walking chain A in order, which node is the first one that also belongs to chain B?

Hint 2

Walk chain B once and remember every label you see in a set, then walk chain A and stop at the first label found in that set.

Hint 3

Compare labels, not values, and note that equal starts, or a start lying inside the other chain, need no special handling with this approach. For constant extra space, consider aligning chain lengths or switching pointers to the other chain's start when one runs out.