Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Decode a string like 3[a2[c]] where k[...] repeats the bracket content k times.
Problem: Decode a string like 3[a2[c]] where k[...] repeats the bracket content k times.
def decode(s):
st, cur, k = [], '', 0
for ch in s:
if ch.isdigit(): k = k * 10 + int(ch)
elif ch == '[': st.append((cur, k)); cur, k = '', 0
elif ch == ']':
prev, n = st.pop(); cur = prev + cur * n
else: cur += ch
return cur
print(decode("3[a2[c]]"), decode("2[ab]3[x]y"), len(decode("10[a]")))What is printed?- A. acacac ababxxxy 10
- B. accaccacc ababxxxy 10
- C. accaccacc abxxxy 10
- D. accaccacc ababxxxy 1
Correct answer: B. accaccacc ababxxxy 10
Push the string built so far and the repeat count at '['; at ']' repeat the inner string and append it to the saved prefix. 2[c] → cc, a + cc = acc, ×3. Counts can have several digits (10). Output-size bound: O(length of the result).
More Coding Interview Problems questions
- Problem: For each element, find the next greater element in a circular array (−1 if none). python def ngecircular(a): n = len(a); res =…
- Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today's price. python def spans(p)…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Problem: Check whether two strings are isomorphic (characters map one-to-one consistently). python def iso(s, t): return len(set(s)) ==…
- Problem: Find the minimum number of swaps to sort an array of distinct values. python def minswaps(a): order = sorted(range(len(a))…
- Problem: Count the distinct values taken by the bitwise OR of all contiguous subarrays. python def distinctor(a): res, cur = set(), set()…