Search Insert Position in C++

C++Server Side ProgrammingProgramming

Suppose we have a sorted array arr and a target value, we have to find the index when the target is found. If that is not present, then return the index where it would be if it were inserted in order.

So, if the input is like [1,3,4,6,6], and target = 5, then the output will be 3, as we can insert 5 at index 3, so the array will be [1,3,4,5,6,6]

To solve this, we will follow these steps−

  • n := size of A

  • if n < 1, then −

    • return 0

  • low := 0, high := n - 1

  • while low <= high, do −

    • mid := low + (high - low) /2

    • if A[mid] is same as target, then −

      • return mid

    • otherwise when A[mid] > target, then −

      • high := mid - 1, pos := mid

    • otherwise

      • low := mid + 1, pos := mid + 1

  • return pos

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int searchInsert(vector<int>& A, int target) {
      int n = A.size();
      if(n < 1) {
         return 0;
      }
      int low = 0;
      int high = n-1;
      int mid;
      int pos;
      while(low <= high) {
         mid = low + (high-low)/2;
         if(A[mid] == target) {
            return mid;
         }
         else if(A[mid] > target) {
            high = mid - 1;
            pos = mid;
         }
         else {
            low = mid + 1;
            pos = mid + 1;
         }
      }
      return pos;
   }
};
main(){
   Solution ob;
   vector<int&g; v = {1,3,4,6,6};
   cout << (ob.searchInsert(v,5));
}

Input

{1,3,4,6,6},5

Output

3
raja
Published on 10-Jun-2020 12:04:41
Advertisements