educative.io

Solution with a single loop

Another approach is to add index parameter to elements in the waiting list. Then we will only put the element back in the heap, if its index is far enough.

def schedule_tasks(tasks, k):
  intervalCount = 0
  freqMap = Counter(tasks)
  h = []
  for task, count in freqMap.items():
    heappush(h, (-count, task))
  
  q = deque()
  while h or q:
    if len(q) > 0 and q[0][2] < intervalCount - k:
      count, task, _ = q.popleft()
      heappush(h, (count, task))

    if len(h) > 0:
      count, task = heappop(h)
      if count + 1 < 0:
        q.append((count + 1, task, intervalCount))
    
    intervalCount += 1
  
  return intervalCount

Some comments would be helpful. :slight_smile: