Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.
"(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:
keyi and the bracket pair with the key's corresponding valuei.keyi and the bracket pair with a question mark "?" (without the quotation marks).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.
Example 1:
Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]] Output: "bobistwoyearsold" Explanation: The key "name" has a value of "bob", so replace "(name)" with "bob". The key "age" has a value of "two", so replace "(age)" with "two".
Example 2:
Input: s = "hi(name)", knowledge = [["a","b"]] Output: "hi?" Explanation: As you do not know the value of the key "name", replace "(name)" with "?".
Example 3:
Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]] Output: "yesyesyesaaa" Explanation: The same key can appear multiple times. The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". Notice that the "a"s not in a bracket pair are not evaluated.
Constraints:
1 <= s.length <= 1050 <= knowledge.length <= 105knowledge[i].length == 21 <= keyi.length, valuei.length <= 10s consists of lowercase English letters and round brackets '(' and ')'.'(' in s will have a corresponding close bracket ')'.s will be non-empty.s.keyi and valuei consist of lowercase English letters.keyi in knowledge is unique.Problem summary: 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 "?" (without the quotation marks). 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
"(name)is(age)yearsold" [["name","bob"],["age","two"]]
"hi(name)" [["a","b"]]
"(a)(a)(a)aaa" [["a","yes"]]
apply-substitutions)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1807: Evaluate the Bracket Pairs of a String
class Solution {
public String evaluate(String s, List<List<String>> knowledge) {
Map<String, String> d = new HashMap<>(knowledge.size());
for (var e : knowledge) {
d.put(e.get(0), e.get(1));
}
StringBuilder ans = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') {
int j = s.indexOf(')', i + 1);
ans.append(d.getOrDefault(s.substring(i + 1, j), "?"));
i = j;
} else {
ans.append(s.charAt(i));
}
}
return ans.toString();
}
}
// Accepted solution for LeetCode #1807: Evaluate the Bracket Pairs of a String
func evaluate(s string, knowledge [][]string) string {
d := map[string]string{}
for _, v := range knowledge {
d[v[0]] = v[1]
}
var ans strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '(' {
j := i + 1
for s[j] != ')' {
j++
}
if v, ok := d[s[i+1:j]]; ok {
ans.WriteString(v)
} else {
ans.WriteByte('?')
}
i = j
} else {
ans.WriteByte(s[i])
}
}
return ans.String()
}
# Accepted solution for LeetCode #1807: Evaluate the Bracket Pairs of a String
class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d = {a: b for a, b in knowledge}
i, n = 0, len(s)
ans = []
while i < n:
if s[i] == '(':
j = s.find(')', i + 1)
ans.append(d.get(s[i + 1 : j], '?'))
i = j
else:
ans.append(s[i])
i += 1
return ''.join(ans)
// Accepted solution for LeetCode #1807: Evaluate the Bracket Pairs of a String
use std::collections::HashMap;
impl Solution {
pub fn evaluate(s: String, knowledge: Vec<Vec<String>>) -> String {
let s = s.as_bytes();
let n = s.len();
let mut map = HashMap::new();
for v in knowledge.iter() {
map.insert(&v[0], &v[1]);
}
let mut ans = String::new();
let mut i = 0;
while i < n {
if s[i] == b'(' {
i += 1;
let mut j = i;
let mut key = String::new();
while s[j] != b')' {
key.push(s[j] as char);
j += 1;
}
ans.push_str(map.get(&key).unwrap_or(&&'?'.to_string()));
i = j;
} else {
ans.push(s[i] as char);
}
i += 1;
}
ans
}
}
// Accepted solution for LeetCode #1807: Evaluate the Bracket Pairs of a String
function evaluate(s: string, knowledge: string[][]): string {
const n = s.length;
const map = new Map();
for (const [k, v] of knowledge) {
map.set(k, v);
}
const ans = [];
let i = 0;
while (i < n) {
if (s[i] === '(') {
const j = s.indexOf(')', i + 1);
ans.push(map.get(s.slice(i + 1, j)) ?? '?');
i = j;
} else {
ans.push(s[i]);
}
i++;
}
return ans.join('');
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.