Coincidence Search in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of unique integers called nums. We have to find the number of integers that could still be successfully found using a standard binary search.

So, if the input is like [2,6,4,3,10], then the output will be 3, as if we use binary search to look for 4, we can find it at first iteration. We can also find 2 and 10 after two iterations.

To solve this, we will follow these steps −

  • Define a function help(), this will take target, an array & nums,

  • low := 0

  • high := size of nums - 1

  • while low <= high, do −

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

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

      • return true

    • if nums[mid] < target, then −

      • low := mid + 1

    • Otherwise

      • high := mid - 1

  • return false

  • From the main method, do the following −

  • ret := 0

  • for each element i in nums

    • ret := ret + help(i, nums)

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool help(int target, vector<int> & nums) {
      int low = 0;
      int high = nums.size() - 1;
      while (low <= high) {
         int mid = low + (high - low) / 2;
         if (nums[mid] == target)
         return true;
         if (nums[mid] < target) {
            low = mid + 1;
         } else {
            high = mid - 1;
         }
      }
      return false;
   }
   int solve(vector<int> & nums) {
      int ret = 0;
      for (int i : nums) {
         ret += help(i, nums);
      }
      return ret;
   }
};
main() {
   Solution ob;
   vector<int> v = {2,6,4,3,10};
   cout << (ob.solve(v));
}

Input

{2,6,4,3,10}

Output

3
raja
Updated on 02-Sep-2020 11:44:29

Advertisements