Evaluate the Bracket Pairs of a String - Problem

You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.

For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age".

You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.

You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:

  • Replace keyi and the bracket pair with the key's corresponding valuei.
  • If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?".

Each key will appear at most once in your knowledge. There will not be any nested brackets in s.

Return the resulting string after evaluating all of the bracket pairs.

Input & Output

Example 1 — Basic Replacement
$ Input: s = "(name)is(age)yearsold", knowledge = [["name","Bob"],["age","20"]]
Output: "Bobis20yearsold"
💡 Note: The key "name" is replaced with "Bob" and "age" is replaced with "20", resulting in "Bobis20yearsold"
Example 2 — Unknown Key
$ Input: s = "hi(name)", knowledge = [["age","25"]]
Output: "hi?"
💡 Note: The key "name" is not found in knowledge, so it's replaced with "?"
Example 3 — No Brackets
$ Input: s = "hello", knowledge = [["name","Bob"]]
Output: "hello"
💡 Note: No bracket pairs found, so the string remains unchanged

Constraints

  • 1 ≤ s.length ≤ 105
  • 0 ≤ knowledge.length ≤ 105
  • knowledge[i].length == 2

Visualization

Tap to expand
Evaluate the Bracket Pairs of a StringInput String:"(name)is(age)yearsold"nameageKnowledge Array:["name", "Bob"]["age", "20"]Replace bracket pairs with corresponding valuesOutput:"Bobis20yearsold"
Understanding the Visualization
1
Input
String with bracket pairs and knowledge array
2
Process
Find bracket pairs and lookup values
3
Output
String with replacements or '?' for unknown keys
Key Takeaway
🎯 Key Insight: Use hash map to transform O(n×k) linear searches into O(n+k) with constant-time lookups
Asked in
Facebook 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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