15. The Missing Ticket

A raffle sold tickets numbered 0, 1, 2, ..., n, one ticket for each number. Exactly one ticket was lost before the draw, and the remaining n tickets were collected in a box in no particular order.

Write a method missingNumber that takes the array nums of the n ticket numbers found in the box and returns the number of the one ticket that is missing.

Example 1

Input:
nums = [3,0,1]
Output:
2
Explanation:

The tickets 0 to 3 should all be present, but 2 is not in the box.

Example 2

Input:
nums = [0,1]
Output:
2
Explanation:

Tickets 0 and 1 are present, so the lost ticket is number 2.

Constraints

1 ≤ nums.length ≤ 1000

All values in nums are distinct and lie between 0 and nums.length inclusive

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…