Search In Rotated Sorted Array
You have been given a sorted array/list ARR consisting of ‘N’ elements. You are also given an integer ‘K’.
Now the array is rotated at some pivot point unknown to you. For example, if ARR = [ 1, 3, 5, 7, 8]. Then after rotating ARR at index 3, the array will be ARR = [7, 8, 1, 3, 5].
Now, your task is to find the index at which ‘K’ is present in ARR.
Note :
1. If ‘K’ is not present in ARR then print -1.
2. There are no duplicate elements present in ARR.
3. ARR can be rotated only in the right direction.
For example, if ARR = [12, 15, 18, 2, 4] and K = 2, then the position at which K is present in the array is 3 (0-indexed).
Follow Up
Can you do this in Logarithmic time and constant additional space?
Input Format
The first line of input contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains two single-space separated integers ‘N’ and ‘K’, respectively.
The second line of each test case contains ‘N’ single space-separated integers, denoting the elements of the array/list ARR.
Output Format :
For each test case return the index at which K is present in ARR.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 5000
0 <= K <= 10^5
0 <= ARR[i] <= 10^5
Time Limit : 1 second
CodingNinjas
author
2y
Naive Approach
Naively traverse the array and find if ‘K’ is present in ARR or not. If ‘K’ is present in ARR return its index else return -1.
Space Complexity: O(1)Explanation:O(1), i.e. constant space...read more
CodingNinjas
author
2y
Binary Search
The key observation here is that after rotating ARR, it is divided into two sorted parts/arrays, one from 0 to pivot - 1 another from pivot to N - 1.
Now the problem boils down to finding ...read more
Help your peers!
Add answer anonymously...
Top Qualcomm Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Qualcomm Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app