← Questions

Days needed to finish recurring tasks

0
AmazonCoding

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^5
  • 1 <= intervals[i] <= 10^5
  • 1 <= 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 goal be smaller than n, so the answer is day 1?
  • Can the count of runs exceed 32-bit integers while searching? (It can, with 10^5 tasks.)
  • Are the intervals all at least 1?

What a strong answer covers

  • Sees that the number of runs by day d is sum((d - 1) // x + 1) over the intervals, which only grows with d, so the answer can be found by binary search on d.
  • Picks safe bounds: lo = 1, and hi at most 1 + (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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding