Random Pick Index in C++


Suppose we have an array of integers with possible duplicates, we have to pick the index randomly of a given target number. We can assume that the given target number must exist in the array. So if the array is like [1,2,3,3,3], then pick(3), may return 2, 3, 4 randomly.

To solve this, we will follow these steps −

  • ret := - 1, cnt := 1

  • for i in range 0 to size of v

    • if v[i] = target, then

      • if random number mod cnt = 0, then ret = i

      • cnt := cnt + 1

  • return ret

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   vector <int> v;
   Solution(vector<int>& nums) {
      srand(time(NULL));
      v = nums;
   }
   int pick(int target) {
      int ret = -1;
      int cnt = 1;
      for(int i = 0; i < v.size(); i++){
         if(v[i] == target){
            if(rand() % cnt++ == 0) ret = i;
         }
      }
      return ret;
   }
};
main(){
   vector<int> v = {1,2,3,3,3};
   Solution ob(v);
   cout << (ob.pick(3));
}

Input

Initialize with [1,2,3,3,3]
Call pick(3) to get random index positions

Output

4
3
4
2

Updated on: 02-May-2020

435 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements