← Questions

Most optional tasks under a daily time limit

0
AmazonCodingLast asked Sep 2025

A coding interview question asked in Amazon's online assessment, last asked Sep 2025. It tests greedy and sorting.

Every day has the same time limit. Each day must run its required task; if time is left, it can also run at most one optional task. There are n days, each with its required duration, and n optional tasks, each usable once on any day where it fits. Return the most optional tasks you can schedule without any day going over the limit, and one assignment that achieves it.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • schedule_optional(limit: int, required: list[int], optional: list[int]) -> tuple[int, list[int]] — the count, and for each day the duration of the optional task placed on it, or -1 for none. Any optimal assignment is accepted.

An optional task of duration o fits on day i only if required[i] + o <= limit.

Example

schedule_optional(7, [4, 5, 2, 4], [5, 6, 3, 4])   ->  (2, [3, -1, 4, -1])
# room per day: 3, 2, 5, 3. Only the 3 fits in a room of 3, and only one 3 exists;
# day 2 (room 5) takes the 4. Days 1 and 3 get nothing.

schedule_optional(7, [7, 7, 7], [1, 2, 3])         ->  (0, [-1, -1, -1])

schedule_optional(10, [3, 8, 1, 6], [2, 7, 4, 9])  ->  (4, [7, 2, 9, 4])

Constraints

  • 0 <= n <= 10^5; 1 <= limit <= 10^9; 0 <= required[i], optional[i] <= 10^9.

Clarifying questions

  • Can a day run more than one optional task? (Not in the base problem.)
  • What if a required task alone is longer than the limit?
  • Is any optimal assignment accepted, or a specific one?

What a strong answer covers

  • Each day offers room limit - required[i]; the task is a matching between rooms and durations where a duration fits a room at least as large.
  • Greedy: sort rooms and durations ascending; go through rooms from smallest to largest and give each the shortest unused duration that fits (two pointers). An exchange argument shows it never loses. O(n log n).
  • Building the assignment by keeping each room's original day index.
  • Days with no room, and a required task longer than the limit (report the plan as impossible, or treat that day as having no room).

Follow-ups

  • Each optional task is tied to its own day (optional[i] only on day i).
  • Up to k optional tasks per day, all within the day's remaining time.
  • Maximise the total optional time scheduled instead of the count.

Where it's asked

  • Amazon · Online assessment · Last asked Sep 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

greedy · sorting

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