Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Split a string into as many parts as possible so each letter appears in at most one part; return the part sizes.
Problem: Split a string into as many parts as possible so each letter appears in at most one part; return the part sizes.
def parts(s):
last = {c: i for i, c in enumerate(s)}
out, start, end = [], 0, 0
for i, c in enumerate(s):
end = max(end, last[c])
if i == end:
out.append(end - start + 1); start = i + 1
return out
print(parts("abacbdefegdhij"))What is printed?- A. [5, 9]
- B. [3, 2, 6, 1, 1, 1]
- C. [5, 6, 3]
- D. [5, 6, 1, 1, 1]
Correct answer: D. [5, 6, 1, 1, 1]
Each part must extend to the last occurrence of every letter it contains. 'abacb' ends at 4 (last b). 'defegd' ends at the last d (index 10). h, i, j are each alone. O(n).
More Coding Interview Problems questions
- Problem: Jobs have deadlines and profits; each takes one unit of time. Schedule to maximise profit (greedy by profit, latest free slot)…
- Problem: Given n ≤ 10⁵ intervals, find the minimum number of points such that every interval contains at least one point. Which greedy…
- Problem: Given n balloons as horizontal intervals, find the minimum number of vertical arrows that burst all of them (a balloon bursts if…
- Problem: Insert a new interval into a sorted list of non-overlapping intervals, merging if necessary. python def insert(iv, new): out, i…
- Problem: n ≤ 10⁵ trains arrive and depart at given minutes. Find the minimum number of platforms. Which approach is O(n log n) and correct?
- Problem: Assign cookies of sizes s to children with greed factors g (a child is content if cookie ≥ greed). Maximise content children…