
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Missing Element in a Sorted Array of Consecutive Numbers in C++
Concept
With respect of a given array array[] of n distinct integers, elements are placed sequentially in ascending order with one missing element. Our task is to determine the missing element.
Input
array[] = {1, 2, 3, 4, 5, 6, 7, 9}
Output
8
Input
array[] = {-4, -2, -1, 0, 1, 2}
Output
-3
Input
array[] = {1, 2, 3, 4}
Output
-1
No element is missing.
Method
Principles
Look for inconsistency: According to this principle, the difference between any element and its index must be array[0] for every element.
Example,
A[] = {1, 2, 3, 4, 5} -> Consistent
B[] = {201, 202, 203, 204} -> Consistent
C[] = {1, 2, 3, 5, 6} -> Inconsistent as C[3] – 3 != C[0] i.e. 5 – 3 != 1
Determining inconsistency helps to scan only half of the array each time in O(logN).
Algorithm
Determine middle element and verify if it’s consistent.
-
If middle element is consistent, then verify if the difference between middle element and its next element is higher than 1 i.e. verify if array[mid + 1] – array[mid] > 1
If yes, then array[mid] + 1 is the missing element.
Else, we have to scan the right half array from the middle element and jump to step-1.
-
If middle element is inconsistent, then verify if the difference between middle element and its previous element is higher than 1 i.e. verify if array[mid] – array[mid – 1] > 1
If yes, then array[mid] – 1 is the missing element.
Else, we have to scan the left half array from the middle element and jump to step-1.
Example
// CPP implementation of the approach #include<bits/stdc++.h> using namespace std; // Shows function to return the missing element int findMissing(int array[], int n1){ int low = 0, high = n1 - 1; int mid1; while (high > low){ mid1 = low + (high - low) / 2; // Verify if middle element is consistent if (array[mid1] - mid1 == array[0]){ // Here, no inconsistency till middle elements // When missing element is just after // the middle element if (array[mid1 + 1] - array[mid1] > 1) return array[mid1] + 1; else{ // Go right low = mid1 + 1; } } else{ // Here inconsistency found // When missing element is just before // the middle element if (array[mid1] - array[mid1 - 1] > 1) return array[mid1] - 1; else{ // Go left high = mid1 - 1; } } } // Here, no missing element found return -1; } // Driver code int main(){ int array[] = { -9, -8, -6, -5, -4, -3, -2, -1, 0 }; int n1 = sizeof(array)/sizeof(array[0]); cout <<"The Missing Element:" <<(findMissing(array, n1)); }
Output
The Missing Element:-7