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 scopeexitScope()- Exit the current scopedeclare(name, value)- Declare a variable in the current scopelookup(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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code