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, wherechapter[i]is the duration in minutes required to read chapteri(0-indexed). Chapters must be completed strictly in sequential order (0, 1, ..., len(chapter) - 1).evening, whereevening[j]is your reading budget in minutes on nightj + 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
1offers3minutes, which is shorter than the4-minute opening chapter, so nothing is completed and those3minutes expire. Night2offers7minutes, enough to finish chapters0and1(4 + 3 = 7). Night3offers5minutes, finishing the2-minute final chapter right away; night4is never needed.
Example 2
- Input:
chapter = [6, 9, 4], evening = [8, 5, 7, 9] - Output:
-1 - Explanation: Night
1(8minutes) completes the6-minute first chapter and drops the remaining2minutes. Nights2(5minutes) and3(7minutes) are both too short for the9-minute second chapter. Night4(9minutes) finishes the second chapter, but no nights remain for the4-minute final chapter.
Example 3
- Input:
chapter = [2, 5, 6, 4], evening = [8, 6, 4] - Output:
3 - Explanation: Night
1completes the first two chapters (2 + 5 = 7 <= 8, discarding1leftover minute), night2completes the6-minute third chapter, and night3completes the4-minute fourth chapter.
Constraints
1 <= len(chapter), len(evening) <= 100,0001 <= chapter[i], evening[j] <= 10^9
Step-by-step walkthrough
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), andevening, 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-1if evenings run out with at least one chapter still unread.Track progress with a forward-only bookmark index
A tempting first draft copies
chapterinto a list and callsunread.pop(0)whenever a chapter finishes. In Python,list.pop(0)shifts every remaining element one slot to the left, costingO(N)work per chapter andO(N^2)total across100,000chapters!Instead, leave
chapteruntouched and maintain a single integer pointerchapter_idxmarking the next unread chapter. Advancingchapter_idx += 1takesO(1)time andO(1)extra space.total_chapters = len(chapter) # chapter_idx: 0-based index of the next unread chapter (0 -> total_chapters) chapter_idx = 0Why the nested `while` inside `for` runs in linear `O(N + M)` time
On each evening, we set
remaining_minutes = available_minutesand advancechapter_idxin awhileloop as long aschapter_idx < total_chaptersandchapter[chapter_idx] <= remaining_minutes.Even though a
whileloop sits inside aforloop, trace howchapter_idxmoves 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_idxnever moves backward, thewhilebody executes at mostNtimes in total across allMevenings combined, and the stopping check at the end of an evening runs at most once per evening (Mtimes). Total work isO(N + M).Handle exact-fit minutes (`<=`) and 1-based early return
Two boundary details deserve careful attention inside each evening's loop:
- Exact fit (
<=, not<): Whenremaining_minutes == 3andchapter[chapter_idx] == 3, the chapter finishes right at the end of the evening (3 <= 3). Using<would mistakenly postpone it. - Immediate 1-based return: Checking
if chapter_idx == total_chapters:right after thewhileloop returnsevening_idx + 1on 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- Exact fit (
Complete solution
Putting the bookmark index, evening loop, early return, and
-1fallback 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_idxstarts at0and increments at mostNtimes across all evenings combined, while the outerforloop runs at mostMevenings 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]): Checkingif chapter_idx == total_chapters:at the end of each evening returns3right away instead of continuing into evening4. - Book finishes on the very first evening (
chapter = [2, 3, 5], evening = [10, 4]): All chapters finish duringevening_idx = 0, returning0 + 1 = 1. - Total evening minutes exceed total chapter minutes, yet book still fails (
chapter = [6], evening = [5, 5, 5]): None of the5-minute evenings can hold a6-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<=onchapter[chapter_idx] <= remaining_minutesfinishes the second chapter when3 <= 3reducesremaining_minutesto0. - Billion-minute inputs (
10^9per chapter and evening): Subtractingchapter[chapter_idx]fromremaining_minuteskeeps values within[0, 10^9]with zero risk of overflow even in 32-bit languages.
Common mistakes
- Returning
evening_idxinstead ofevening_idx + 1: Python'senumeratestarts at0, whereas the problem asks for the 1-based evening number (1for the first evening). - Writing
< remaining_minutesinstead of<= remaining_minutes: Strict<refuses to read a5-minute chapter during a5-minute evening even though it finishes right on time. - Popping from index
0of a Pythonlist(chapter.pop(0)): Shifting up to100,000elements per chapter makes a single massive evening time out inO(N^2). - Carrying
remaining_minutesinto the next evening: Forgetting to resetremaining_minutes = available_minutesat the top of theforloop 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 whereP[k]stores the sum of the firstkchapters, withP[0] = 0) once inO(N)time. On an evening with budgetBstarting atchapter_idx, any reachable ending indexendsatisfiesP[end] - P[chapter_idx] <= B, orP[end] <= P[chapter_idx] + B; binary search (repeatedly halving the sorted arrayPwithbisect_right(P, P[chapter_idx] + B) - 1to find the cutoff inO(log N)comparisons) jumps across thousands of chapters inO(log N)time per evening, answering each schedule query inO(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 anM-bit integermaskand storingdp[mask]= the furthestchapter_idxreachable with that subset) transitions via prefix-sum binary search inO(2^M * M * log N)time; anymaskreachingtotal_chapterswith 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 leastminutes_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 inO(log N)time per evening (O(N + M log N)overall).
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?
- 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?
- How would your algorithm change if a one-time bookmark pass allowed splitting at most one chapter across two back-to-back evenings?
Similar questions
- Minimum Insertions for Target Subsequence
- Tally Exam Score Tiers
- Smallest Vehicle Fleet for Booking Intervals
- Fewest Clear Cells Across an Eight-Way Grid
- Linear Track Robot Collisions
- Last Assigned Locker Number
More Google interview questions
- Smallest Vehicle Fleet for Booking Intervals Medium
- Minimum Absolute Array Sum Easy
- Tally Exam Score Tiers Easy Pro
- Minimum Event Chairs Easy Pro
- Dining Waitlist Manager Hard Pro
- Four-Digit PINs with Target Digit Sum Easy Pro
- Filesystem Subtree Byte Usage Medium Pro
- Token Row Score Easy Pro
- Highest-Sum Subarray with Matching Ends Medium Pro
- Navigating an Engineering Project With Open-Ended Requirements Medium Pro