MediumNo. 1807

Evaluate the Bracket Pairs of a String — LeetCode 1807 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
Reading time
3 min

The 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".

Example

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".

Python solution

PythonSolution
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)

Complexity

Time
O(n + m)
Space · auxiliary
O(L)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1807. Evaluate the Bracket Pairs of a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy
0522Longest Uncommon Subsequence IIMedium

Frequently asked questions

How hard is LeetCode 1807. Evaluate the Bracket Pairs of a String?

LeetCode 1807. Evaluate the Bracket Pairs of a String is rated Medium on LeetCode.

What is the time complexity of LeetCode 1807. Evaluate the Bracket Pairs of a String?

The Python solution on this page runs in O(n + m).

What is the space complexity of LeetCode 1807. Evaluate the Bracket Pairs of a String?

The Python solution on this page uses O(L) auxiliary space.

What topics does LeetCode 1807. Evaluate the Bracket Pairs of a String cover?

LeetCode 1807. Evaluate the Bracket Pairs of a String is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.