The torn-out table of contents
- O(n) · Medium
- Full plan
- Python
- JavaScript
- strings
- regular expressions
- lists
Problem
A second-hand book arrived at Fermín's bookstore with half a table of contents: someone tore pages out of it and only a few lines were left. Before he puts it in the window, Fermín wants to know which chapters went missing.
Write a function that takes contents, the list of the lines that were left, each one a string. The list may be empty. A chapter line has the word Chapter, then a space, then the chapter number, and at the end the page where it starts, as in "Chapter 3 ... 45". There are also lines for other parts of the book, like "Prologue ... 7", and the word Chapter does not always open the line: "Part two, Chapter 4 ... 60" is a chapter too. Of the numbers on a line, the chapter is the one next to the word Chapter; the rest are pages.
Return the list of the chapters that do not show up, from lowest to highest, counting from 1 and up to the highest chapter that does show up. With ["Prologue ... 7", "Chapter 1 ... 11", "Chapter 4 ... 38"] you return [2, 3]: the 1 and the 4 are there, the 2 and the 3 are not, and from the 5 on nothing is asked.
If none is missing, or if the table of contents has no chapter at all, you return an empty list. The book does not go past 20 chapters.
Examples
The example
["Prologue ... 7", "Chapter 1 ... 11", "Chapter 4 ... 38"] → [2, 3]
None is missing
["Chapter 1 ... 5", "Chapter 2 ... 9", "Chapter 3 ... 14"] → []
The word sits in the middle of the line
["Chapter 1 ... 9", "Part two, Chapter 3 ... 45"] → [2]
The page is not the chapter
["Chapter 2 ... 11"] → [1]
The table of contents has no chapters
["Prologue ... 3", "List of maps ... 121"] → []
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def missing_chapters(contents):
passJavaScript
function missingChapters(contents) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.