Example 5: Missing Number

TopicDifficultyCompanies
Recursion and Divide & Conquer Approach
EASY
Amazon
Yahoo

Given an array arr[] consists of 0, 1, 2, 3, 4,.....n. But one of the numbers is missing in it. Write a program to find the number that is missing from the array.

Problem Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

NOTE:

All the elements in the array are distinct.

There will be only one missing number in the given array, two missing numbers will not be there. Also, if there is no missing number then you have to return the number that is coming just after the largest element of the array.

Example 1

Input: arr[] = [4, 3, 1, 2]
Output: 0
Explanation: The array should have elements 0, 1, 2, 3, 4 but 0 is missing. So, the answer is 0.

Example 2

Input: arr[] = [4, 5, 0, 6, 1, 7, 3]
Output: 2
Explanation: All the numbers except 2 are present in the given array consisting of 0, 1, 2..7

Example 3

Input: arr[] = [4, 3, 1, 0, 2]
Output: 5
Explanation: All distinct elements 0, 1, 2, 3, 4, 5 should be present in the array but 5 is missing. So, the answer is 5.

Code Editor

Practice and Learn

Best way to learn is through solving real problems. Practice this problem in this code editor.