Symbol Table Implementation - Problem

Implement a symbol table that supports nested scopes using a Binary Search Tree (BST). Your symbol table should support the following operations:

Operations:

  • enterScope() - Enter a new scope
  • exitScope() - Exit the current scope
  • declare(name, value) - Declare a variable in the current scope
  • lookup(name) - Find the value of a variable (searches current scope, then parent scopes)

Each scope maintains its own BST for fast variable lookups. When looking up a variable, search the current scope first, then parent scopes in order until found.

Input: A sequence of operations as an array of arrays. Each operation is ["operation_name", ...args]

Output: An array containing the results of all lookup operations (null for other operations)

Input & Output

Example 1 — Basic Scope Operations
$ Input: operations = [["enterScope"], ["declare", "x", 10], ["lookup", "x"], ["enterScope"], ["declare", "x", 20], ["lookup", "x"], ["exitScope"], ["lookup", "x"]]
Output: [null, null, 10, null, null, 20, null, 10]
💡 Note: Enter scope, declare x=10, lookup returns 10. Enter nested scope, declare x=20 (shadows parent), lookup returns 20. Exit scope, lookup finds parent x=10.
Example 2 — Variable Shadowing
$ Input: operations = [["declare", "y", 5], ["enterScope"], ["declare", "y", 15], ["lookup", "y"], ["exitScope"], ["lookup", "y"]]
Output: [null, null, null, 15, null, 5]
💡 Note: Declare y=5 globally, enter scope, declare y=15 (shadows global), lookup finds 15. Exit scope, lookup finds original y=5.
Example 3 — Missing Variable
$ Input: operations = [["enterScope"], ["declare", "a", 1], ["lookup", "b"]]
Output: [null, null, null]
💡 Note: Enter scope, declare variable 'a', but lookup for 'b' returns null since 'b' doesn't exist in any scope.

Constraints

  • 1 ≤ operations.length ≤ 104
  • Variable names are non-empty strings with lowercase letters only
  • -106 ≤ variable values ≤ 106
  • Lookup operations will only occur when at least one scope exists
  • ExitScope operations will not make scopes empty (global scope always remains)

Visualization

Tap to expand
INPUT OPERATIONS["declare", "x", 10]["enterScope"]["declare", "x", 20]["lookup", "x"]["exitScope"]BST SCOPE STACK1Global BSTx:102Nested BSTx:20Lookup: Search current→parentRESULTS ARRAY[null, // declare x=10 null, // enterScope null, // declare x=2020, // lookup finds 20 null] // exitScopeFound x = 20in current scope BSTKey Insight:Each scope uses a BST for O(log n) variable lookup, with scope chain traversal for proper variable shadowingTutorialsPoint - Symbol Table Implementation | BST Approach
Asked in
Google 15 Microsoft 12 Amazon 10 Meta 8
23.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen