Missing Element in Sorted Array in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 13-Apr-2020 08:32:38
Advertisements