The Missing Exam Paper

EasymathAlso known as Missing Number

Before an exam you print one paper per student, numbered 1, 2, 3 and so on. Afterwards the stack is one paper short: somebody walked out with theirs.

The papers came back in drop-off order. Find the missing number without sorting the pile.

Your task

Write missingPaper(papers). You printed papers.length + 1 papers, numbered 1 to papers.length + 1. The list holds every number except one, each at most once, in any order. Return the missing number.

If the list is empty, you printed only paper 1, and it is missing.

missingPaper(papers: int[]) → int

Examples

Example 1
Input
papers = [4, 2, 5, 1]
Output
3
Why

Four papers came back, so five were printed: 1 to 5. Every number except 3 is on the desk.

Example 2
Input
papers = [1, 2, 3]
Output
4
Why

Four papers were printed. The pile 1, 2, 3 has no gap inside, so the missing one is the last, 4. Looking only for a gap between neighbours would miss this.

Example 3
Input
papers = []
Output
1
Why

Nothing came back, so only paper 1 was printed, and it is missing.

Constraints

  • 0 ≤ papers.length ≤ 100,000
  • 1 ≤ papers[i] ≤ papers.length + 1
  • All numbers in papers are different, and exactly one number from the range is absent.
Start with brute force

For each number from 1 to n + 1, scan the pile for it. The first one you cannot find is the answer.

That is up to n + 1 scans of n papers: about 10 billion reads for 100,000 papers. Sorting and looking for the gap is O(n log n), still more work than needed.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code