Search Element in a Rotated Sorted Array

Given a sorted array that has been rotated, the task is to find the index of a specific element. The array is initially sorted in ascending order and then rotated clockwise by an unknown amount.

For example, a sorted array [1, 2, 3, 4, 5] rotated by 2 positions becomes [4, 5, 1, 2, 3].

You are required to answer multiple queries where for each query, you will search a particular element and return its index if found; otherwise, return -1.

Your goal is to achieve this in O(logN) time complexity for each query.

Input:

N
A1 A2 A3 ... AN
Q
Q1
Q2
...
QQ

Output:

An integer representing the index of the searched element for each query, or -1 if the element is not found.

Example:

Input:
N = 5
A = 4 5 1 2 3
Q = 2
key = 1
key = 6
Output:
2
-1

Constraints:

  • 1 <= N <= 106
  • -109 <= A[i] <= 109
  • 1 <= Q <= 500
  • -109 <= Q[i] <= 109
  • Time Limit: 1 sec
Note:
You only need to return the result, as printing is handled elsewhere.
AnswerBot
5mo

Search for an element in a rotated sorted array efficiently in O(logN) time complexity.

  • Implement binary search to find the pivot point where rotation occurs.

  • Divide the array into two subarrays and per...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Practo

Q. Given an integer n, return true if it is a power of two. Otherwise, return false...read more
Q. Implement a queue using two stacks.
Q. Given a table "student" with columns Name and Marks, write an SQL query to get t...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits