Days needed to finish recurring tasks
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests binary-search, math and arrays.
You run n recurring tasks. Task i runs for the first time on day 1 and then again every intervals[i] days, so it runs on days 1, 1 + intervals[i], 1 + 2 * intervals[i], .... Any number of task runs can happen on the same day.
Given intervals and a target goal, return the smallest day d such that the total number of task runs on days 1 through d is at least goal.
def min_days(intervals: list[int], goal: int) -> int: ...
Constraints
1 <= len(intervals) <= 10^51 <= intervals[i] <= 10^51 <= goal <= 10^9
Example 1
intervals = [3, 5], goal = 5 -> 7
The 3-day task runs on days 1, 4, 7. The 5-day task runs on days 1, 6. By day 6 there are 4 runs; day 7 brings the total to 5.
Example 2
intervals = [2, 2, 2], goal = 7 -> 5
All three tasks run on days 1, 3, 5. That is 3 runs by day 1, 6 by day 3, and 9 by day 5, so day 5 is the first day with at least 7.
Clarifying questions
- Is day 1 the first day every task runs, even for a task with a very long interval?
- Can
goalbe smaller thann, so the answer is day 1? - Can the count of runs exceed 32-bit integers while searching? (It can, with
10^5tasks.) - Are the intervals all at least 1?
What a strong answer covers
- Sees that the number of runs by day
dissum((d - 1) // x + 1)over the intervals, which only grows withd, so the answer can be found by binary search ond. - Picks safe bounds:
lo = 1, andhiat most1 + (goal - 1) * min(intervals), since the fastest task alone reaches the goal by then. - Each check is O(n), so the total is O(n log(goal * min_interval)).
- Can speed up each check by grouping equal intervals with a counter.
- Tests: both examples, a goal reached on day 1, a single task, all intervals 1, and a brute-force day-by-day count for small inputs.
Follow-ups
- Each task starts on its own day, not day 1.
- Each run takes a number of days, and a task can't run again until it finishes.
- Answer many different goals for the same intervals.
- Find the day when the runs reach the goal for each task on its own.
Where it's asked
What it tests
binary-search · math · arrays
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
