Evaluate the Bracket Pairs of a String - Problem
String Template Evaluation Challenge
You're given a template string containing bracket pairs like
Here's how it works:
• Each bracket pair
• If a key doesn't exist in your knowledge base, replace it with
• No nested brackets exist, so parsing is straightforward
Example: Given string
This is a common pattern in template engines and string interpolation systems!
You're given a template string containing bracket pairs like
(name) and (age), along with a knowledge base that maps keys to their values. Your task is to evaluate and replace all bracket pairs with their corresponding values from the knowledge base.Here's how it works:
• Each bracket pair
(key) should be replaced with its corresponding value• If a key doesn't exist in your knowledge base, replace it with
"?"• No nested brackets exist, so parsing is straightforward
Example: Given string
"(name) is (age) years old" and knowledge [["name","Bob"],["age","two"]], the result should be "Bob is two years old".This is a common pattern in template engines and string interpolation systems!
Input & Output
example_1.py — Basic Template
$
Input:
s = "(name)is(age)yearsold"
knowledge = [["name","Bob"],["age","two"]]
›
Output:
"Bobistwoyearsold"
💡 Note:
The bracket pair (name) is replaced with "Bob" and (age) is replaced with "two", resulting in "Bobistwoyearsold"
example_2.py — Unknown Key
$
Input:
s = "hi(name)"
knowledge = [["we","us"]]
›
Output:
"hi?"
💡 Note:
The key "name" is not found in the knowledge array, so (name) is replaced with "?"
example_3.py — Multiple Replacements
$
Input:
s = "(a)(a)(a)aaa"
knowledge = [["a","yes"]]
›
Output:
"yesyesyesaaa"
💡 Note:
All three bracket pairs (a) are replaced with "yes", while the literal characters "aaa" remain unchanged
Visualization
Tap to expand
Understanding the Visualization
1
Build Database Index
Convert knowledge array into fast lookup table (hash map)
2
Scan Template
Process string character by character, identifying bracket pairs
3
Replace Placeholders
For each bracket pair, extract key and lookup replacement value
4
Handle Missing Keys
Use '?' for keys not found in knowledge base
Key Takeaway
🎯 Key Insight: Hash tables transform expensive O(k) searches into O(1) lookups, making the overall algorithm linear in the combined input size.
Time & Space Complexity
Time Complexity
O(n + k)
O(k) to build hash map + O(n) to process string with O(1) lookups
✓ Linear Growth
Space Complexity
O(k)
Hash map stores k key-value pairs from knowledge array
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 105
- 0 ≤ knowledge.length ≤ 105
- knowledge[i].length == 2
- 1 ≤ knowledge[i][0].length, knowledge[i][1].length ≤ 10
- s consists of lowercase English letters and round brackets '(' and ')'
- All the keys in knowledge are unique
- There are no nested brackets in s
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code