#1807

Evaluate the Bracket Pairs of a String

Medium
ArrayHash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the string while leveraging a HashMap for quick lookups of keys. This reduces the time complexity significantly by avoiding nested loops.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a HashMap from the knowledge array for O(1) access to values.
  2. 2Step 2: Initialize an empty result string and a pointer to traverse the input string.
  3. 3Step 3: As you iterate through the string, check for '(' to identify keys.
  4. 4Step 4: When a key is found, extract it and look it up in the HashMap, appending the corresponding value or '?' to the result.
  5. 5Step 5: Continue until the end of the string, then return the result.
solution.py16 lines
1def evaluate(s, knowledge):
2    knowledge_map = {k: v for k, v in knowledge}
3    result = ''
4    i = 0
5    while i < len(s):
6        if s[i] == '(':  
7            j = i
8            while s[j] != ')':
9                j += 1
10            key = s[i+1:j]
11            result += knowledge_map.get(key, '?')
12            i = j + 1
13        else:
14            result += s[i]
15            i += 1
16    return result

Complexity note: The complexity is O(n) because we only traverse the string once, and lookups in the HashMap are O(1).

  • 1Using a HashMap allows for quick lookups of values associated with keys.
  • 2Iterating through the string once is more efficient than nested iterations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.