Count the Nodes in a Chain Reachable Only Through Left and Right Links
AppleSoftware Engineer · Technical ScreenLast updated
Starting from one node of a chain in which every node links only to its left and right neighbors, count the nodes in the whole chain. It tests traversal in both directions from an arbitrary node, handling of chain ends and single-node chains, and the design of your own test cases.
A chain of nodes is linked in a line. Each node can reach only its two neighbors, the node on its left and the node on its right; there is no head pointer, no stored length and no list of all nodes. You are handed one node somewhere in the chain. Count the nodes in the whole chain.
For this console, nodes are numbered, and the nodes of several separate chains are given together. links[i] = [left, right] holds the numbers of node i's left and right neighbors, with -1 where there is no neighbor on that side. Starting from node start, return the number of nodes in the chain that contains it.
The interviewer also expected you to write your own test cases.
Function Signature
def count_chain_nodes(links: list[list[int]], start: int) -> int:
Rules
- The links are consistent: for any two nodes
iandj,links[i][1] == jexactly whenlinks[j][0] == i. In words,jis the right neighbor ofiexactly wheniis the left neighbor ofj. - Every chain is a straight line with two ends. Following right links from any node ends at a node whose right neighbor is
-1, and following left links ends at a node whose left neighbor is-1; no chain closes into a loop. - A node whose two neighbors are both
-1forms a chain of one node. - The count includes
startitself.
Constraints
1 <= n <= 10^5, wheren = len(links)- Each
links[i]has exactly two entries; each entry is-1or an integer in[0, n - 1], and never equalsi 0 <= start < n
Examples
Example 1
Input: links = [[-1, 1], [0, 2], [1, 3], [2, -1]], start = 2
Output: 4
From node 2, the left side holds nodes 1 and 0 and the right side holds node 3, so the chain is 0, 1, 2, 3.
Example 2
Input: links = [[2, -1], [-1, 3], [4, 0], [1, -1], [-1, 2]], start = 0
Output: 3
Node 0 has no right neighbor; to its left are node 2 and then node 4, which has no left neighbor. The chain is 4, 2, 0. Nodes 1 and 3 form a separate chain and are not counted.
Example 3
Input: links = [[-1, -1]], start = 0
Output: 1
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.