Trace a Named Value Through a Chain of Symbol Bindings
Arrays & HashingAuto-graded · 21 test casesLast updated
Tests whether a candidate can resolve a target symbol to its integer value by following an arbitrarily ordered, acyclic chain of name-to-name and name-to-literal bindings.
You are given a list of bindings and a target symbol name. Each binding pairs a symbol name with either a decimal integer literal or another symbol name. Your job is to find the integer value that the target ultimately represents.
Bindings can appear in any order. A symbol may point to another symbol, which may point to yet another, forming a chain. Every chain ends at an integer literal.
Task
Implement lookup_symbol(bindings, target) that returns the integer value reached by following the chain starting at target.
Input
bindings: a list of two-element string lists[symbol, definition].symbolis the name being defined.definitionis either an integer literal or another symbol name.
target: the name of the symbol to resolve.
Symbol names match the pattern [A-Za-z_][A-Za-z0-9_]* — they begin with a letter or underscore and contain only letters, digits, and underscores.
Integer literals consist of an optional leading minus sign followed by one or more decimal digits, with no spaces or plus sign. Literal values fall within [-1000000000, 1000000000].
Output
Return the single integer value at the end of the chain starting from target.
Constraints
1 <= len(bindings) <= 100000- Each string is at most 40 characters long.
- Every symbol name across all bindings is unique.
targetis guaranteed to be defined.- Every symbol referenced in a definition is also defined.
- The binding graph is acyclic: following references from any symbol will always reach a literal in a finite number of steps.
- Malformed definitions and cycles will not appear in any test case.
Examples
Example 1
Input: lookup_symbol([['T1', 'T2'], ['T2', '-8'], ['unused', '4']], 'T1')
Output: -8
Example 2
Input: lookup_symbol([['A', '007'], ['B', 'A']], 'B')
Output: 7
Example 3
Input: lookup_symbol([['value', '0']], 'value')
Output: 0
Hints
Hint 1
Build a lookup table from all the bindings before you start resolving. Scanning the full list on every hop turns an O(n) problem into O(n²).
Hint 2
You need to decide at each step whether a definition string is a literal or another symbol name. The input grammar makes the first character enough: literals start with '-' or a digit; symbol names never do.
Hint 3
Use a loop rather than recursion. A chain can be up to 100,000 hops long, which will exceed Python's default recursion limit if you resolve it recursively.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core observation is that every binding is one of exactly two things: a name mapped to a literal, or a name mapped to another name. Together they form a collection of chains, each terminating at a literal. Resolving target means walking its chain until you hit that terminal literal.
Step 1 — Build a hash map
Load all bindings into a dictionary keyed by symbol name. This gives O(1) access to any symbol's definition regardless of the order in which bindings appear. Skipping this step and scanning the list on every hop would cost O(n) per hop, making a worst-case chain O(n²) — around 10¹⁰ operations at the maximum input size.
Step 2 — Classify each definition by its first character
The two grammars have completely disjoint first characters:
- A literal starts with
'-'or a digit ('0'–'9'). - A symbol name starts with a letter or
'_'.
A single character check is exact and needs no regular expressions or try/except around int().
Step 3 — Walk the chain iteratively
Start at target. At each step, look up the current symbol's definition. If it is a literal, convert and return it. Otherwise it is a symbol name — make it the new current symbol and repeat.
The loop must be iterative rather than recursive. Chains can be up to 100,000 hops long, which would overflow Python's default recursion limit (~1000 frames).
Why the loop always terminates
The binding graph is acyclic and every referenced symbol is defined. Each iteration moves to a new symbol that has never been visited. With at most n symbols, a literal is reached within n steps.
Correctness notes
- Order independence: the full map is built before resolution begins, so definition order never matters.
- Leading zeros:
int("007")correctly yields7. - Negative zero:
int("-0")correctly yields0. - Unused bindings: symbols that are never reached are loaded into the map but never visited — they cause no harm.
Complexity
- Time: O(n · L) where n is the number of bindings and L ≤ 40 is the maximum string length. Building the map hashes each name once; traversal visits at most n symbols with one lookup each. Since L is a small constant, this is effectively O(n).
- Space: O(n) for the dictionary. The traversal itself uses O(1) extra space.
Reference solution
from typing import List
def lookup_symbol(bindings: List[List[str]], target: str) -> int:
# Build a dict for O(1) definition lookups regardless of binding order.
table = {symbol: definition for symbol, definition in bindings}
current = target
while True:
definition = table[current]
# Literals always start with '-' or a digit; symbol names never do.
if definition[0] == '-' or definition[0].isdigit():
return int(definition)
# The definition is another symbol name — keep following the chain.
current = definition
Tracing through the first sample
Bindings: [["T1","T2"],["T2","-8"],["unused","4"]], target "T1".
table["T1"]→"T2". First char is'T'— a symbol name. Move to"T2".table["T2"]→"-8". First char is'-'— a literal. Returnint("-8")= -8.