Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Decode a string where k[s] means s repeated k times (brackets can nest).
Problem: Decode a string where k[s] means s repeated k times (brackets can nest).
def decode(s):
st, cur, k = [], "", 0
for c in s:
if c.isdigit(): k = k * 10 + int(c)
elif c == '[': st.append((cur, k)); cur, k = "", 0
elif c == ']':
prev, n = st.pop(); cur = prev + cur * n
else: cur += c
return cur
print(decode("2[ab3[c]]x"))What is printed?- A. abcabcabcx
- B. abcccabcccx
- C. abcccx
- D. abcccabcccxx
Correct answer: B. abcccabcccx
The inner 3[c] becomes 'ccc', so 2[abccc] becomes 'abcccabccc', and the trailing x is appended once: 'abcccabcccx'. The stack stores the text built before each '[' with its multiplier.
More Coding Interview Problems questions
- Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs. python def calc(s): res, num…
- Problem: Remove duplicate letters so that each letter appears once and the result is the lexicographically smallest possible subsequence…
- Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half). python import heapq def…
- Which statement about selecting the k-th smallest of n unsorted numbers is correct?
- Problem: Find the smallest divisor d such that Σ ceil(a[i] / d) ≤ threshold. python def smallestdiv(a, t): lo, hi = 1, max(a) while lo <…
- Problem: Buses i take time[i] minutes per trip and run independently and repeatedly. Find the minimum time for all buses together to…