Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Split a string into as many parts as possible so that each letter appears in at most one part; return the part sizes.
Problem: Split a string into as many parts as possible so that each letter appears in at most one part; return the part sizes.
def parts(s):
last = {c: i for i, c in enumerate(s)}
res, start, end = [], 0, 0
for i, c in enumerate(s):
end = max(end, last[c])
if i == end:
res.append(i - start + 1); start = i + 1
return res
print(parts("xyxzwzqpqrr"))What is printed?- A. [3, 3, 5]
- B. [3, 3, 3, 2]
- C. [2, 1, 3, 3, 2]
- D. [3, 8]
Correct answer: B. [3, 3, 3, 2]
x forces the first part to reach index 2; z (last at 5) forces 'zwz'; q (last at 8) forces 'qpq'; 'rr' closes the string. Parts: 3, 3, 3, 2.
More Coding Interview Problems questions
- How many structurally different binary search trees can be built on the keys 1..7 if the ROOT must be 3?
- Problem: Count the ways to tile a 2 × n board with 2 × 1 dominoes and L-shaped trominoes (both rotatable). python def tilings(n): dp = [1…
- What is the time complexity of this loop? python i = n while i > 0: for j in range(i): work() # O(1) i //= 2
- Recursive quicksort can need O(n) stack depth on adversarial input. Which change GUARANTEES O(log n) extra stack space even in the worst…
- Problem: Find the shortest substring of s that contains every character of t, counting duplicates (return the leftmost one on ties)…
- Problem: Count subarrays with EXACTLY k distinct values using exactly(k) = atMost(k) − atMost(k − 1). python def atmost(a, k): cnt, l, res…