KatInterview

Walking Both Ways to Measure a Doubly Linked Chain

Linked ListsAuto-graded · 21 test cases
MediumAuto-gradedLinked Listslinked-listtraversaltwo-pointers

Last updated

Given neighbor links for a group of disjoint chains, count how many nodes sit in the chain containing a given start node.

You are given a set of separate chains. Every node in a chain points only at its immediate neighbours — the one to its left and the one to its right. There is no head, no stored size, and no other way to enumerate the nodes.

The chains are described by an array links, where links[i] = [left, right] gives the index of node i's left neighbour and right neighbour. An entry of -1 means there is no neighbour on that side.

Given the index start of some node, return how many nodes belong to the chain that contains it. Count start itself.

Guarantees

  • The links are mutually consistent: links[i][1] == j if and only if links[j][0] == i.
  • Every chain is a straight line with two distinct ends; following right links always terminates at a node whose right neighbour is -1, and following left links always terminates at a node whose left neighbour is -1. No chain loops back on itself.
  • A node whose neighbours are both -1 is a chain of a single node.
  • Nodes of different chains are never joined by a link.

Input / Output

Return a single integer: the size of the chain containing start.

Constraints

  • 1 <= n <= 10^5, where n = len(links)
  • Each links[i] has exactly two entries, each either -1 or an integer in [0, n - 1], and never equal to i
  • 0 <= start < n

Examples

Example 1

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

Output: 4

Example 2

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

Output: 3

Example 3

Input: chain_length_from_node([[-1, -1]], 0)

Output: 1

Hints

Hint 1

The chain is a line, so every node is either start, to its left, or to its right — three disjoint groups you can handle separately.

Hint 2

Walk one direction at a time using the appropriate column of links; stop as soon as the neighbour is -1.

Hint 3

Count start as 1 before you start walking, and never visit a node twice, so no visited set is needed.