Find first and last positions of an element in a sorted array.


Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.


Note: If the number x is not found in the array just print '-1'.

Input:
The first line consists of an integer T i.e number of test cases. The first line of each test case contains two integers n and x. The second line contains n spaced integers.

Output:
Print index of the first and last occurrences of the number with a space in between.

Constraints: 
1<=T<=100
1<=n,a[i]<=1000


Solution Hunt:

    

    // Here we are giving a function only.

 

1:     vector<int> searchRange(vector<int>& nums, int target)   
2:    {    
3:      vector<int> a;  
4:      if(binary_search(nums.begin(),nums.end(),target))  
5:      {  
6:        a.push_back(lower_bound(nums.begin(),nums.end(),target)-nums.begin());  
7:        a.push_back(upper_bound(nums.begin(),nums.end(),target)-nums.begin()-1);  
8:      }  
9:      else  
10:      {  
11:        a.push_back(-1);  
12:        a.push_back(-1);  
13:      }  
14:      return a;  
15:    }  

Post a Comment

1 Comments

If you have any doubt then let me know.