Search In Rotated Sorted Array
Aahad and Harshit always have fun by solving problems. Harshit took a sorted array consisting of distinct integers and rotated it clockwise by an unknown amount. For example, he took a sorted array = [1, 2, 3, 4, 5] and if he rotates it by 2, then the array becomes: [4, 5, 1, 2, 3].
After rotating a sorted array, Aahad needs to answer Q queries asked by Harshit, each of them is described by one integer Q[i]. which Harshit wanted him to search in the array. For each query, if he found it, he had to shout the index of the number, otherwise, he had to shout -1.
For each query, you have to complete the given method where 'key' denotes Q[i]. If the key exists in the array, return the index of the 'key', otherwise, return -1.
Note:
Can you solve each query in O(logN) ?
Input Format:
The first line of input contains the size of the array: N
The second line contains N single space-separated integers: A[i].
The third line of input contains the number of queries: Q
The next Q lines of input contain: the number which Harshit wants Aahad to search: Q[i]
Output Format:
For each test case, print the index of the number if found, otherwise -1.
Output for every test case will be printed in a separate line.
Note:
You are not required to explicitly print the expected output, just return it and printing has already been taken care of.
Constraints:
1 <= N <= 10^6
-10^9 <= A[i] <= 10^9
1 <= Q <= 10^5
-10^9 <= Q[i] <= 10^9
Time Limit: 1sec
CodingNinjas
author
2y
1. My first approach was to decide which side of the list is sorted.
2. after finding out sorted side, I applied if condition to check correct side of the element.
3. then Applied binary search in the r...read more
CodingNinjas
author
2y
Brute Force Approach
The idea here is to do a linear approach which apparently is a brute force way to do this.
- Visit every element one by one.
- Check if the current element that you are looking at is the...read more
CodingNinjas
author
2y
Binary Search Approach
Before we discuss the algorithm, there's an interesting property about sorted and rotated arrays that must be noted.
If we divide the array into two halves, at least one of the ...read more
Anonymous
4mo
def search_in_rotated_sorted_array(nums, target): left, right = 0, nums.size - 1 while left <= right...read more
Add answer anonymously...
Top Flipkart Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Flipkart 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