Search an element in sorted and rotated array | Practice | GeeksforGeeks

Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element K. The task is to find the index of the given element K in the array A.
Example 1:
Input:
N = 9
A[] = {5 6,7,8,9,10,1,2,3}
K = 10
Output: 5
Explanation: 10 is found at index 5.

Example 1:
Input:
N = 3
A[] = {3,1,2}
K = 1
Output: 1
User Task:
Complete Search() function and return the index of the element K if found in the array. If the element is not present, then return -1.
Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 107
0 ≤ Ai ≤ 108
1 ≤ K ≤ 108
0
awrijeetsingh12021 hour ago
//USING ARRAY REPRESENTATION OF BINARY TREE. PARENT AT i, LEFT CHILD AT 2*i+1, RIGHT CHILD AT 2*i+2.

int Search(vector<int> vec, int K) {
    
    int i, n = vec.size();
	for (i = 0; i < n / 2; i++)
	{
		if (vec[i] == K)
		{
			return i;
		}
		if (2 * i + 1 < n && vec[2 * i + 1] == K)
		{
			return 2 * i + 1;
		}
		if (2 * i + 2 < n && vec[2 * i + 2] == K)
		{
			return 2 * i + 2;
		}
	}
	return -1;
}
0
baldevshai
This comment was deleted.
0
aloksinghbais021 week ago
C++ solution having time complexity as O(log(N)) and space complexity as O(1) is as follows :- 
 
Execution Time :- 0.27 / 1.5 sec
 
int Search(vector<int> vec, int K) {   int n = vec.size();   int s = 0;   int e = n-1;   while(s <= e){       int mid = (s+e)/2;              if(vec[mid] == K) return (mid);       else if(vec[mid] >= vec[0]){           if(K < vec[mid] && K >= vec[0]){               e = mid - 1;           }           else{               s = mid + 1;           }       }       else if(vec[mid] <= vec[n-1]){           if(K > vec[mid] && K <= vec[n-1]){               s = mid + 1;           }           else{               e = mid - 1;           }       }   }   return (-1);}
0
subhajitghosh19971 week ago
// JAVA SOLUTION // ALL TEST CASE PASS
// ITERATIVE APPROACH
class Solution 
{ 
    static int Search(int array[], int target)
	{
	    // code here
	    int low = 0 , high = array.length -1;
	    int x = -20;
	    while(low <= high){
	        int mid = (low+high)/2;
	        if(array[mid] == target){
	            x = mid;
	            return x;
	        }
	        if(array[low] < array[mid]){
	            if(target >= array[low] && target < array[mid]){
	                high = mid - 1;
	            }else{
	                low = mid + 1;
	            }
	        }else{
	            if(target > array[mid] && target <= array[high]){
	                low = mid + 1;
	            }else{
	                high = mid - 1;
	            } 
	        }
	        
	    }
	    if(x != -20){
	        return x;
	    }
	    
	    return -1;
	}
} 


+1
amiransarimy1 month ago
Python Solution
 
def Search(arr,n,k):
   
   low, high = 0, n -1
   
   while low <= high:
       mid = low +(high-low)//2
       if arr[mid] == k:
           return mid
       
       if arr[low] < arr[mid]:
           if k >= arr[low] and k < arr[mid]:
               high = mid-1
           else:
               low = mid + 1
       
       else:
           if k > arr[mid] and k <= arr[high]:
               low = mid +1
           
           else:
               high = mid - 1
   
   return -1
+1
abhinavsinghbiz2 months ago
C++ Code; O(logN) && O(1); Run Time=0.3sec
This question is based on Modified Binary search
 
int Search(vector<int> vec, int K) {   int n=vec.size();   int low=0,high=n-1;   while(low<=high){       int mid=(low+high)/2;       if(vec[mid]==K){           return mid;       }       if(vec[low]<vec[mid]){           if(K>=vec[low] && K<vec[mid]){               high=mid-1;           }           else{               low=mid+1;           }       }       else{           if(K>vec[mid] && K<=vec[high]){               low=mid+1;           }           else{               high=mid-1;           }       }   }   return -1;}
-3
abhinavsinghbiz2 months ago
C++ Code; O(N) && O(1) ;Run Time=0.3sec 
 
int Search(vector<int> vec, int K) {   int n=vec.size();   for(int i=0;i<n;i++){       if(vec[i]==K){           return i;       }   }   return -1;
-4
shivaay319coder2 months ago
Easy to Understand Solution: - 
int Search(vector<int> vec, int K) {
    //code here
    int count = 0;
    for(auto x:vec){
        count++;
        if(x == K)
            return count-1;
    }
    return -1;
}
Please upvote if you find this helpful!!
0
lindan1232 months ago
int Search(vector<int> vec, int K) {
    int n = vec.size();
    unordered_map<int,int> m;
    for(int i=0;i<n;i++)
    {
        m[vec[i]]=i;
    }
    if(m.find(K)==m.end())
    {
        return -1;
    }
    return m[K];
}
Time Taken : 0.6sec
cpp
+2
akashmr10962 months ago
First find faulty index using binary search
Then do binary search on element on two different arrays separated on faulty index
 
class Solution 
{ 
    static int Search(int array[], int target)
	{
	    int faultyIndex = findFaultyIndex(array, 0, array.length-1);
	    
	    if (faultyIndex == -1) {
	        return binarySearch(array, target, 0, array.length-1);
	    } else {
	        int idx = binarySearch(array, target, 0, faultyIndex-1);
	        idx = idx == -1 ? binarySearch(array, target, faultyIndex, array.length-1) : idx;
	        return idx;
	    }
	}
	
	static int binarySearch(int arr[], int target, int start, int end) {
	    if (start > end) {
	        return -1;
	    }
	    
	    int pivot = (start+end)/2;
	    if(arr[pivot] == target) {
	        return pivot;
	    } else if(arr[pivot] < target) {
	        return binarySearch(arr, target, pivot+1, end);
	    } else {
	        return binarySearch(arr, target, start, pivot-1);
	    }
	}
	static int findFaultyIndex(int arr[], int start, int end) {
	    
	    if (start > end) {
	        return -1;
	    }
	    
	    if ((start + 1) == end) {
	        int idx = -1;
	        if (start != 0) {
	            idx = arr[end] < arr[start] ? start : idx;
	        } 
	        if (end != arr.length-1) {
	            idx = arr[end] < arr[start] ? end: idx; 
	        }
	        return idx;
	    }
	    
	    int pivot = (start+end)/2;
	    
	    if (arr[pivot] > arr[start] && arr[end] > arr[pivot]) {
	        return -1;
	    }
	    
	    if (arr[pivot] < arr[start]) { // lies on the left side
	        return findFaultyIndex(arr, start, pivot);
	    } else {
	        return findFaultyIndex(arr, pivot, end);
	    }
	}
} 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.