← Questions

Minimum daily reading pace to finish a textbook

0
AmazonCoding

A coding interview question asked at Amazon. It tests binary-search, arrays and greedy.

A student must read a textbook of n chapters before an exam. Chapter i has pages[i] pages, and the chapters must be read in order.

The student picks a daily limit x. On each day they read from the current chapter until either the chapter ends or they have read x pages, whichever comes first. A day never continues into the next chapter: if a chapter ends partway through the day, the student stops for that day.

Given pages and the number of days days left before the exam, return the smallest positive integer x that lets the student finish every chapter within days days. Return -1 if no x works.

Implement:

def min_pages_per_day(pages: list[int], days: int) -> int: ...

Constraints

  • 1 <= n <= 10^5
  • 1 <= pages[i] <= 10^9
  • 1 <= days <= 10^9

Example 1

pages = [7, 2, 6], days = 6
output: 3

With x = 3 the student needs 3 + 1 + 2 = 6 days. With x = 2 they need 4 + 1 + 3 = 8 days, which is too many.

Example 2

pages = [4, 9], days = 1
output: -1

Each chapter takes at least one day, so two chapters cannot fit in one day.

Clarifying questions

  • Is a day that finishes a chapter early still a full day?
  • Is -1 only for days < n, or are there other impossible cases?
  • Does the answer need to fit in 64 bits (pages up to 10^9)?
  • Is x = max(pages) always enough when days >= n?

What a strong answer covers

  • Sees that with limit x chapter i takes ceil(pages[i] / x) days, so the total is a non-increasing function of x.
  • Returns -1 when days < n, since each chapter takes at least one day; otherwise binary searches x in [1, max(pages)], where x = max(pages) gives exactly n days.
  • Each check is O(n) with integer ceiling, so O(n log max(pages)) in total.
  • Tests both examples, one chapter, days == n, and very large page counts.

Follow-ups

  • A day may continue into the next chapter.
  • Each day has its own page limit.
  • Return the plan: which pages are read on which day.

Where it's asked

What it tests

binary-search · arrays · greedy

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