← Accenture bank

Accenture · Question 57 · Backtracking

Task Scheduler

BacktrackingC++code⏱ O(N + 26 log 26)💾 O(1)
Service-based

Problem

Given a list of tasks and cooldown n, find the least intervals needed to finish all tasks without running the same task within cooldown.

Approach

Calcu late idle slots using the frequency of the most frequent task.

Time O(N + 26 log 26)Space O(1)

How it works

  1. 1Count frequencies; the max sets the slot frame.
  2. 2Other tasks fill idle slots; leftovers add idle time.

Sample input / output

Input:
tasks = ["A","A","A","B","B","B"], n = 2
Output:
8

Constraints

1 <= tasks.length <= 10^4; tasks A-Z; 0 <= n <= 100.

Solution — read it, then walk it

Time O(N + 26 log 26)Space O(1)Loops 2Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <iostream>include <vector>include <algorithm>using namespace stdDEFINEleastInterval(std::vector<char>&tasks, int n)std::vector<int> freq(26,0)for (char t : tasks)freq[t - 'A']++std::sort(freq.begin(),freq.end())DEFINE max_freq = freq[25]DEFINE idle_time =(max_freq - 1) * nfor (int i = 24; i >=0 && idle_time > 0;--i)idle_time -=std::min(freq[i], max_freq- 1)idle_time = std::max(0,idle_time)RETURN idle_time +tasks.size()DEFINE main()std::vector<char> tasks ={'A', 'A', 'A', 'B', 'B','B'}cout <<leastInterval(tasks, 2) <<endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/19

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits