205. Python Program to Find the Missing Number from 1 to N
MediumPhase 2 · Practice
This one takes a few steps, with split(), a for loop and a little maths. You know all three.
Overview
Finding the missing number is a classic interview question. There is a short way to solve it with sums, and interviewers like to see it.
Problem Statement
Priya hands out tickets with the numbers 1 to n. At the end of the day, all the tickets come back except one. They come back in any order.
Read n on the first line and the returned ticket numbers on the second line. Print Missing number: <number>.
Examples
Example 1. Input:
5
3 1 5 4
gives:
Missing number: 2
Why: 1 + 2 + 3 + 4 + 5 is 15. The numbers on line 2 add up to 13, and 15 - 13 is 2.
Example 2. Input:
4
1 2 3
gives:
Missing number: 4
Why: 1, 2 and 3 are all there, so the missing number is the last one, 4.
Input
Two lines. Line 1: the whole number n (2 or more). Line 2: n - 1 different whole numbers from 1 to n, with one space between them, in any order. Exactly one number from 1 to n is missing. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: Missing number: <number>. The tests try 7 different inputs, also a missing first number and a missing last number.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.