Walking Both Ways to Measure a Doubly Linked Chain
Linked ListsAuto-graded · 21 test casesLast 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] == jif and only iflinks[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
-1is 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, wheren = len(links)- Each
links[i]has exactly two entries, each either-1or an integer in[0, n - 1], and never equal toi 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The chain is a straight line, so from start there are exactly three disjoint sets of nodes to account for: start itself, everything lying to its left, and everything lying to its right.
So count start as one, then make two independent walks:
- Take
links[start][0]as the cursor and keep following the left column while the cursor is not-1, adding one per node visited. - Reset the cursor to
links[start][1]and do the same with the right column.
The sum of the three groups is the answer. No visited set, recursion, or full scan of links is needed.
Why it is correct. Because each chain is a line, any node in the same chain as start is reached from start by repeatedly taking left links, or repeatedly taking right links, or is start itself. The left walk enumerates precisely the nodes to the left of start in order, and the right walk does the same on the right. Neither walk can revisit a node or leak into another chain: the walks move strictly in one direction, chains contain no cycles, and consistent links mean a link never crosses between chains. Termination is guaranteed because both directions eventually hit -1.
Complexity. Time is O(k) where k is the length of the chain containing start (at most n) — each node of that chain is visited once, and other chains are never touched. Extra space is O(1): a counter and a cursor. The walk must be iterative; with up to 10^5 nodes, recursion would exceed Python's recursion limit.
Watch out for. Do not start the counter at 0 and then also count the neighbour walks from start — that double-counts. Do not assume node i's neighbours are i - 1 and i + 1; numbering is arbitrary. Do not count nodes outside the chain, which is what a whole-array scan would do when several chains exist.
from typing import List
def chain_length_from_node(links: List[List[int]], start: int) -> int:
total = 1
cur = links[start][0]
while cur != -1:
total += 1
cur = links[cur][0]
cur = links[start][1]
while cur != -1:
total += 1
cur = links[cur][1]
return total