
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 the only missing number in a sorted array using C++
In this problem, we are given an arr[] of size N containing values from 1 to N with one value missing in the array. Our task is to find the only missing number in a sorted array.
Let’s take an example to understand the problem,
Input
arr[] = {1, 2, 3, 5, 6, 7}
Output
4
Solution Approach
A simple solution to the problem is by traversing the sorted array linearly. And then check for the missing value using the fact that arr[i] = (i + 1).
Example 1
Program to illustrate the working of our solution
#includeusing namespace std; int findMissingValArray(int arr[], int N){ for(int i = 0; i < N; i++){ if(arr[i] != (i+1)) return (i+1); } return -1; } int main(){ int arr[] = {1, 2, 3, 4, 6}; int N = sizeof(arr)/sizeof(arr[0]); cout<<"The missing value from the array is "< Output
The missing value from the array is 5Another approach to solve the problem is using binary search and checking the value at mid. If the value at mid is mid+1 and value at (mid - 1) is (mid) then we will traverse the left subarray and vise versa.
Example 2
Program to illustrate the working of our solution
#includeusing namespace std; int findMissingValArray(int arr[], int N){ int s = 0, e = N - 1; while (s <= e) { int mid = (s + e) / 2; if (arr[mid] != mid + 1 && arr[mid - 1] == mid) return (mid + 1); if (arr[mid] != (mid + 1)) e = (mid - 1); else s = (mid + 1); } return -1; } int main(){ int arr[] = {1, 2, 3, 4, 6}; int N = sizeof(arr)/sizeof(arr[0]); cout<<"The missing value from the array is "< Output
The missing value from the array is 5
Advertisements