The Missing Exam Paper

EasymathAlso known as Missing Number

Before an exam you print one paper per student and number them 1, 2, 3 and so on. Afterwards the stack on your desk is one paper short: somebody walked out without handing theirs in.

The papers came back in whatever order students dropped them off. You want to know which number is missing without sorting the whole pile.

Your task

Write missingPaper(papers). You printed papers.length + 1 papers, numbered from 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 a single paper, number 1, and it is the one 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, 2, 3, 4, 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 goes 1, 2, 3 with no gap inside it, so the missing one is the last number, 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 to see if it is there. The first number you cannot find is the answer.

Each scan reads up to n papers, and you may do n + 1 scans. With 100,000 papers that is about 10 billion reads. Sorting first and looking for the gap is better, O(n log n), but it still does more work than the problem needs.

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