Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 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 Output
The missing value from the array is 5
Advertisements
