Ctrl K

Fill In Bracketed Keys

Medium
You are given a template text: a string of lowercase English letters and digits that contains pairs of round brackets. Each pair holds a non-empty key; for example, in hi(name) the key is name. Brackets are never nested. You also get a dictionary known, where known[i] = [key, value] says that key maps to value. Each key appears in known at most once. Replace every bracket pair together with its key by the key's value. If the key is not in known, replace the brackets and the key with a single ?. Characters outside brackets stay as they are. Return the resulting string.
Example 1
text="dear(who)see(day)", known=[["who", "anna"], ["day", "monday"]] → 'dearannaseemonday'

(who) becomes anna, and (day) becomes monday.

Example 2
text="(x)plus(y)is(x)", known=[["x", "two"]] → 'twoplus?istwo'

The key x appears twice and is replaced by two both times. The value of y is unknown, so it becomes ?.

Example 3
text="nobrackets", known=[] → 'nobrackets'
Constraints
  • 1 ≤ len(text) ≤ 10⁵
  • 0 ≤ len(known) ≤ 10⁵
  • text consists of lowercase English letters, digits and the brackets (, ); the brackets form non-nested pairs, each with a non-empty key inside
  • Keys and values are 1 to 10 characters long: lowercase English letters and digits
  • Keys in known are unique
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAnagram Buckets MediumSplit Into Dictionary Words MediumWords Equal Up to a Shift MediumA Subsequence of One Word Only MediumFiles With the Same Content Medium
loading Python…
Input
text="dear(who)see(day)", known=[["who", "anna"], ["day", "monday"]]
Expected
'dearannaseemonday'

Run checks the first 3 tests in your browser. Submit checks all 79 tests on the server, hidden ones included.