Search in Rotated Sorted Array II
Explore techniques to find a target value in a rotated sorted array of non-distinct integers. Understand how to apply modified binary search to minimize operations and handle duplicates, ensuring an optimal O(n) time and O(1) space solution.
We'll cover the following...
Statement
You are required to find an integer value target in an array arr of non-distinct integers. Before being passed as input to your search function, arr has been processed as follows:
It has been sorted in non-descending order.
It has been rotated around some pivot
, such that, after rotation, it looks like this: [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]. For example,[10, 30, 40, 42, 42, 47, 78, 90, 901], rotated around pivotbecomes [47, 78, 90, 901, 10, 30, 40, 42, 42].
Return TRUE if t exists in the rotated, sorted array arr, and FALSE otherwise, while minimizing the number of operations in the search.
Note: In this problem, the value of
is not passed to your search function.
Constraints
arr.lengtharr[i]arris guaranteed to be rotated at some pivot index.t
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
What is the value of the pivot around which this sorted array has been rotated?
arr = [-10, -9, -7, 20, -29, -21]
3
2
4
6
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.
Try it yourself
Implement your solution in the following coding playground.
We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(n) time and takes O(1) space. You may try to translate the logic of the solved puzzle into a coded solution.
import java.util.*;public class Solution {public static boolean search(int[] arr, int target) {// Replace this placeholder return statement with your codereturn false;}}