Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time.

Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time.
from collections import Counter
def least(tasks, n):
    c = Counter(tasks).values()
    mx = max(c); cnt_mx = sum(1 for v in c if v == mx)
    return max(len(tasks), (mx - 1) * (n + 1) + cnt_mx)
print(least("AAABBB", 2), least("AAABBB", 0), least("AAAABBBCCDE", 2))
What is printed?
  1. A. 8 6 10
  2. B. 6 6 11
  3. C. 8 8 11
  4. D. 8 6 11

Correct answer: D. 8 6 11

The most frequent task forms mx − 1 full frames of size n + 1, plus one slot per task tied for the maximum. AAABBB, n = 2: 2 × 3 + 2 = 8 (AB_AB_AB). With n = 0 no idling is needed: 6. For AAAABBBCCDE: 3 × 3 + 1 = 10 < 11 tasks, so the other tasks fill all gaps and the answer is 11. O(n).

More Coding Interview Problems questions

Exams that ask this topic