Fewest Days to Read a Book When Chapters Cannot Be Split Across Days
OtherSoftware Engineer · Online AssessmentLast updated
Given the reading time available on each day and the time each chapter of a book takes, find the fewest days needed to read every chapter in order when a chapter can never be split across days, or report that the book cannot be finished. It tests simulation with per-day capacity, ordering constraints, and impossible cases.
On any day you may read more than one chapter if you have enough time, but every chapter must be read completely within a single day; a chapter can never be split across days. Return the number of days needed to finish the whole book, or -1 if the book cannot be finished within the given days.
Function Signature
def days_to_finish(time: list[int], book: list[int]) -> int:
Rules
- Chapters are read in order: chapter
j + 1can be started only after chapterjhas been finished. - Days are used in order starting from day
0. You may read nothing on a day. - Reading time does not carry over: time left unused at the end of a day is lost.
- The answer is the smallest
dsuch that the whole book can be read using only days0throughd - 1under these rules. If no suchd <= len(time)exists, return-1. - An empty book needs
0days.
Constraints
1 <= len(time) <= 1000000 <= len(book) <= 1000000 <= time[i] <= 100001 <= book[j] <= 10000
Examples
Example 1
- Input:
time = [3, 5, 2, 6],book = [2, 2, 3, 4] - Output:
4 - Explanation: Day 0 has 3 units: chapter 0 (2 units) fits, but adding chapter 1 would need 4. Day 1 has 5 units: chapters 1 and 2 need exactly 5. Day 2 has 2 units, too few for chapter 3 (4 units). Day 3 has 6 units, and chapter 3 is finished. The book is finished using days 0 through 3, so 4 days are needed, and it cannot be done in fewer.
Example 2
- Input:
time = [4, 4],book = [5] - Output:
-1 - Explanation: The only chapter needs 5 units, but no day offers more than 4, and a chapter cannot be split.
Example 3
- Input:
time = [10, 1],book = [3, 3, 4] - Output:
1 - Explanation: All three chapters need 10 units in total, which fits on day 0.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.