Nightly Chapter Reading

Easy · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

You want to read an entire novel from start to finish across a fixed sequence of nights. You are given two integer lists:

  • chapter, where chapter[i] is the duration in minutes required to read chapter i (0-indexed). Chapters must be completed strictly in sequential order (0, 1, ..., len(chapter) - 1).
  • evening, where evening[j] is your reading budget in minutes on night j + 1 (1-indexed).

Each night, starting from the earliest unread chapter, you complete whole chapters one after another as long as the next unread chapter's duration does not exceed the minutes left in tonight's budget. Partial progress is not allowed: once the next unread chapter takes strictly longer than your remaining minutes for that night, you stop reading for the night and forfeit any leftover minutes.

Compute the 1-based night number (1, 2, ...) on which the last chapter is completed. If one or more chapters remain unread after all nights in evening have elapsed, return -1.

Examples

Example 1

  • Input: chapter = [4, 3, 2], evening = [3, 7, 5, 6]
  • Output: 3
  • Explanation: Night 1 offers 3 minutes, which is shorter than the 4-minute opening chapter, so nothing is completed and those 3 minutes expire. Night 2 offers 7 minutes, enough to finish chapters 0 and 1 (4 + 3 = 7). Night 3 offers 5 minutes, finishing the 2-minute final chapter right away; night 4 is never needed.

Example 2

  • Input: chapter = [6, 9, 4], evening = [8, 5, 7, 9]
  • Output: -1
  • Explanation: Night 1 (8 minutes) completes the 6-minute first chapter and drops the remaining 2 minutes. Nights 2 (5 minutes) and 3 (7 minutes) are both too short for the 9-minute second chapter. Night 4 (9 minutes) finishes the second chapter, but no nights remain for the 4-minute final chapter.

Example 3

  • Input: chapter = [2, 5, 6, 4], evening = [8, 6, 4]
  • Output: 3
  • Explanation: Night 1 completes the first two chapters (2 + 5 = 7 <= 8, discarding 1 leftover minute), night 2 completes the 6-minute third chapter, and night 3 completes the 4-minute fourth chapter.

Constraints

  • 1 <= len(chapter), len(evening) <= 100,000
  • 1 <= chapter[i], evening[j] <= 10^9

Step-by-step walkthrough

  1. Restate the reading rules

    We have chapter, a list of chapter durations in minutes that must be read strictly in order (0, 1, ..., len(chapter) - 1), and evening, a list of time budgets in minutes for each evening.

    On each evening: - Read as many whole unread chapters in a row as fit inside that evening's budget. - Stop for the night as soon as the next unread chapter needs more minutes than remain — leftover minutes are discarded and never carry into tomorrow. - Return the 1-based evening number (1, 2, ...) on which the final chapter finishes, or -1 if evenings run out with at least one chapter still unread.

  2. Track progress with a forward-only bookmark index

    A tempting first draft copies chapter into a list and calls unread.pop(0) whenever a chapter finishes. In Python, list.pop(0) shifts every remaining element one slot to the left, costing O(N) work per chapter and O(N^2) total across 100,000 chapters!

    Instead, leave chapter untouched and maintain a single integer pointer chapter_idx marking the next unread chapter. Advancing chapter_idx += 1 takes O(1) time and O(1) extra space.

    total_chapters = len(chapter)
    # chapter_idx: 0-based index of the next unread chapter (0 -> total_chapters)
    chapter_idx = 0
    
  3. Why the nested `while` inside `for` runs in linear `O(N + M)` time

    On each evening, we set remaining_minutes = available_minutes and advance chapter_idx in a while loop as long as chapter_idx < total_chapters and chapter[chapter_idx] <= remaining_minutes.

    Even though a while loop sits inside a for loop, trace how chapter_idx moves across Example 1 (chapter = [4, 3, 2], evening = [3, 7, 5, 6]):

    chapter = [4, 3, 2]   (total_chapters = 3)
    
    Night 1 (idx 0, 3 min):
      chapter[0] = 4 > 3  -> 0 chapters read, 3 min discarded      (chapter_idx stays 0)
    
    Night 2 (idx 1, 7 min):
      chapter[0] = 4 <= 7 -> rem = 3, chapter_idx = 1
      chapter[1] = 3 <= 3 -> rem = 0, chapter_idx = 2
      chapter[2] = 2 >  0 -> stop for tonight                      (chapter_idx is now 2)
    
    Night 3 (idx 2, 5 min):
      chapter[2] = 2 <= 5 -> rem = 3, chapter_idx = 3 == total_chapters!
      --> return evening_idx + 1 = 3 immediately (Night 4 is never needed)
    

    Because chapter_idx never moves backward, the while body executes at most N times in total across all M evenings combined, and the stopping check at the end of an evening runs at most once per evening (M times). Total work is O(N + M).

  4. Handle exact-fit minutes (`<=`) and 1-based early return

    Two boundary details deserve careful attention inside each evening's loop:

    1. Exact fit (<=, not <): When remaining_minutes == 3 and chapter[chapter_idx] == 3, the chapter finishes right at the end of the evening (3 <= 3). Using < would mistakenly postpone it.
    2. Immediate 1-based return: Checking if chapter_idx == total_chapters: right after the while loop returns evening_idx + 1 on the exact evening the final chapter completes, ignoring any trailing unused evenings.
    for evening_idx, available_minutes in enumerate(evening):
        remaining_minutes = available_minutes
        while chapter_idx < total_chapters and chapter[chapter_idx] <= remaining_minutes:
            remaining_minutes -= chapter[chapter_idx]
            chapter_idx += 1
    
        if chapter_idx == total_chapters:
            return evening_idx + 1
    
  5. Complete solution

    Putting the bookmark index, evening loop, early return, and -1 fallback together gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def solution(chapter: List[int], evening: List[int]) -> int:
        total_chapters = len(chapter)
        # chapter_idx: 0-based index of the next unread chapter (moves forward only, 0 -> total_chapters)
        chapter_idx = 0
    
        # Phase 1: Step through evenings in order, tracking 0-based `evening_idx` and minutes available.
        for evening_idx, available_minutes in enumerate(evening):
            remaining_minutes = available_minutes
    
            # Phase 2: Greedily finish consecutive chapters while the next unread chapter fits in full.
            # Using `<=` includes exact fits where a chapter consumes the final remaining minute.
            while chapter_idx < total_chapters and chapter[chapter_idx] <= remaining_minutes:
                remaining_minutes -= chapter[chapter_idx]
                chapter_idx += 1
    
            # Stop immediately when the final chapter finishes so trailing unused evenings are not counted.
            if chapter_idx == total_chapters:
                return evening_idx + 1
    
            # Any leftover `remaining_minutes` is discarded automatically on the next iteration.
    
        # Phase 3: All evenings were used and at least one chapter is still unread.
        return -1
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of keeping a bookmark in a physical book: every night you open directly to your bookmark, read as many whole chapters as fit before bedtime, move the bookmark forward after each finished chapter, and close the book as soon as the next chapter is too long for tonight's remaining minutes. In code, that bookmark is a single forward-only index chapter_idx, giving us a two-pointer scan (walking across two arrays with indices that only move forward and never reset).

Why does a naive implementation get into trouble? If you remove finished chapters from the front of a Python list with chapter.pop(0) or slicing chapter = chapter[1:], Python copies the remaining elements every time, turning 100,000 chapters into O(N^2) work (~10^10 array shifts). Likewise, you cannot just check sum(evening) >= sum(chapter) because unused leftover minutes are thrown away every night and chapters cannot be split across evenings.

Let's trace chapter = [4, 7, 3] across evening = [6, 5, 7, 4]:

Start: chapter_idx = 0 (bookmark at chapter 0, length 4)

1. Night 1 (6 min): 4 <= 6 -> finish ch 0 (rem = 2), next ch 1 is 7 > 2 -> stop (2 min discarded)
2. Night 2 (5 min): ch 1 is 7 > 5 -> 0 chapters finished (5 min discarded)
3. Night 3 (7 min): 7 <= 7 -> finish ch 1 (rem = 0), next ch 2 is 3 > 0 -> stop
4. Night 4 (4 min): 3 <= 4 -> finish ch 2 -> chapter_idx == 3 (all read!) -> return 4

Complexity

Let N be len(chapter) and M be len(evening).

  • Time: O(N + M). By amortized analysis (summing the total work of an inner operation across the entire run rather than multiplying by the worst single iteration), chapter_idx starts at 0 and increments at most N times across all evenings combined, while the outer for loop runs at most M evenings and performs one stopping check per evening.
  • Space: O(1). We only maintain scalar integer variables (total_chapters, chapter_idx, evening_idx, remaining_minutes) without copying either input list.

Edge cases

  • Book finishes with unused evenings still remaining (chapter = [4, 3, 2], evening = [3, 7, 5, 6]): Checking if chapter_idx == total_chapters: at the end of each evening returns 3 right away instead of continuing into evening 4.
  • Book finishes on the very first evening (chapter = [2, 3, 5], evening = [10, 4]): All chapters finish during evening_idx = 0, returning 0 + 1 = 1.
  • Total evening minutes exceed total chapter minutes, yet book still fails (chapter = [6], evening = [5, 5, 5]): None of the 5-minute evenings can hold a 6-minute chapter, and leftover minutes never roll over, so the loop ends and returns -1.
  • Exact zero-leftover fit (chapter = [4, 3], evening = [7]): Using <= on chapter[chapter_idx] <= remaining_minutes finishes the second chapter when 3 <= 3 reduces remaining_minutes to 0.
  • Billion-minute inputs (10^9 per chapter and evening): Subtracting chapter[chapter_idx] from remaining_minutes keeps values within [0, 10^9] with zero risk of overflow even in 32-bit languages.

Common mistakes

  • Returning evening_idx instead of evening_idx + 1: Python's enumerate starts at 0, whereas the problem asks for the 1-based evening number (1 for the first evening).
  • Writing < remaining_minutes instead of <= remaining_minutes: Strict < refuses to read a 5-minute chapter during a 5-minute evening even though it finishes right on time.
  • Popping from index 0 of a Python list (chapter.pop(0)): Shifting up to 100,000 elements per chapter makes a single massive evening time out in O(N^2).
  • Carrying remaining_minutes into the next evening: Forgetting to reset remaining_minutes = available_minutes at the top of the for loop illegally banks unused minutes from previous evenings.

Follow-up questions

  • How would you answer Q = 100,000 separate schedule queries (each with at most M <= 10 nights) against the same 100,000-chapter book without re-scanning chapters from scratch? Precompute prefix sums P (an array of running totals where P[k] stores the sum of the first k chapters, with P[0] = 0) once in O(N) time. On an evening with budget B starting at chapter_idx, any reachable ending index end satisfies P[end] - P[chapter_idx] <= B, or P[end] <= P[chapter_idx] + B; binary search (repeatedly halving the sorted array P with bisect_right(P, P[chapter_idx] + B) - 1 to find the cutoff in O(log N) comparisons) jumps across thousands of chapters in O(log N) time per evening, answering each schedule query in O(M log N).
  • Suppose you may rearrange the order of the evenings (while still reading chapters in fixed order) to finish the book in the fewest nights possible. How would you solve this when M <= 20? Because chapters must still be read in fixed order and leftover minutes vanish each night, choosing which evening budget to use next matters. For small M (M <= 20), bitmask dynamic programming (representing each subset of already-used evenings as an M-bit integer mask and storing dp[mask] = the furthest chapter_idx reachable with that subset) transitions via prefix-sum binary search in O(2^M * M * log N) time; any mask reaching total_chapters with the smallest set-bit count wins.
  • How would your algorithm change if a one-time bookmark pass allowed splitting at most one chapter across two back-to-back evenings? Maintain three states between evenings: (1) unsplit_idx, the furthest whole chapter finished without using the pass; (2) in_split, a (chapter_idx, minutes_still_needed) pair started with tonight's leftover minutes that only succeeds if tomorrow's evening has at least minutes_still_needed; and (3) after_split_idx, the furthest whole chapter finished once the single split has already completed. Advancing whole-chapter runs with prefix sums and binary search updates all three states in O(log N) time per evening (O(N + M log N) overall).

Follow-up questions

Similar questions

More Google interview questions

All 1125 Google questions →