Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: A CPU runs tasks (letters); identical tasks need at least n idle-or-other slots between them. Find the minimum total time slots.

Problem: A CPU runs tasks (letters); identical tasks need at least n idle-or-other slots between them. Find the minimum total time slots.
from collections import Counter
def least(tasks, n):
    f = Counter(tasks).values(); mx = max(f)
    cnt_mx = sum(1 for v in f if v == mx)
    return max(len(tasks), (mx - 1) * (n + 1) + cnt_mx)
print(least("AAAABBBCCD", 3))
What is printed?
  1. A. 10
  2. B. 13
  3. C. 16
  4. D. 12

Correct answer: B. 13

A appears 4 times, so it needs 3 full frames of length n + 1 = 4 plus a final A: 3 × 4 + 1 = 13. The other 6 tasks fit into the gaps, leaving 3 idle slots. The max(len, …) term matters only when tasks are plentiful enough to fill every gap.

More Coding Interview Problems questions

Exams that ask this topic