KatInterview

Trace a Named Value Through a Chain of Symbol Bindings

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashinghash-mapstring-parsingsimulation

Last 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].
    • symbol is the name being defined.
    • definition is 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.
  • target is 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.