Fewest Days to Read a Book When Chapters Cannot Be Split Across Days
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Online Assessment
You want to read every chapter of a book. The array `time` describes the days available to you: day `i` gives you `time[i]` units of reading time. The array `book` describes the chapters: chapter `j` takes `book[j]` units of time to read.
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
```python
def days_to_finish(time: list[int], book: list[int]) -> int:
```
### Rules
- Chapters are read in order: chapter `j + 1` can be started only after chapter `j` has 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 `d` such that the whole book can be read using only days `0` through `d - 1` under these rules. If no such `d <= len(time)` exists, return `-1`.
- An empty book needs `0` days.
### Constraints
- `1 <= len(time) <= 100000`
- `0 <= len(book) <= 100000`
- `0 <= time[i] <= 10000`
- `1 <= 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.
Overview: 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.
Read the full Software Engineer interview experience this question came from