- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Missing Element in Sorted Array in C++
Suppose we have a sorted array A of unique numbers, we have to find the K-th missing number starting from the leftmost number of the array. So if the array is like [4,7,9,10], and k = 1, then the element will be 5.
To solve this, we will follow these steps −
n := size of the array, set low := 0 and high := n – 1
if nums[n - 1] – nums[0] + 1 – n < k, then
return nums[n - 1] + (k – (nums[n - 1] – nums[0] + 1 – n))
while low < high – 1
mid := low + (high - low)/2
present := mid – low + 1
absent := nums[mid] – nums[low] + 1 – present
if absent >= k then high := mid, otherwise decrease k by absent, low := mid
return nums[low] + k
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int missingElement(vector<int>& nums, int k) { int n = nums.size(); int low = 0; int high = n - 1; if(nums[n - 1] - nums[0] + 1 - n < k) return nums[n - 1] + (k - ( nums[n - 1] - nums[0] + 1 - n)) ; while(low < high - 1){ int mid = low + (high - low) / 2; int present = mid - low + 1; int absent = nums[mid] - nums[low] + 1 - present; if(absent >= k){ high = mid; }else{ k -= absent; low = mid; } } return nums[low] + k; } }; main(){ vector<int> v = {4,7,9,10}; Solution ob; cout << (ob.missingElement(v, 1)); }
Input
[4,7,9,10] 1
Output
5
- Related Articles
- k-th missing element in sorted array in C++
- Find missing element in a sorted array of consecutive numbers in C++
- Find missing element in a sorted array of consecutive numbers in Python
- Single Element in a Sorted Array in C++
- Find the only missing number in a sorted array using C++
- k-th missing element in an unsorted array in C++
- Check for Majority Element in a sorted array in C++
- Element Appearing More Than 25% In Sorted Array in C++
- Maximum element in a sorted and rotated array in C++
- C++ program to search an element in a sorted rotated array
- Finding first unique element in sorted array in JavaScript
- Find index of an extra element present in one sorted array in C++
- Finding missing element in an array of numbers in JavaScript
- Checking for majority element in a sorted array in JavaScript
- Nth smallest element in sorted 2-D array in JavaScript

Advertisements