Search in rotated sorted array-II

Asked atDP WorldPPPragmatic Play
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an integer array nums, sorted in ascending order (may contain duplicate values) and a target value k. Now the array is rotated at some pivot point unknown to you. Return True if k is present and otherwise, return False.

Input : nums = [7, 8, 1, 2, 3, 3, 3, 4, 5, 6], k = 3 Output: True Explanation: The element 3 is present in the array. So, the answer is True.

Input : nums = [7, 8, 1, 2, 3, 3, 3, 4, 5, 6], k = 10 Output: False Explanation:The element 10 is not present in the array. So, the answer is False.

Input : nums = [7, 8, 1, 2, 3, 3, 3, 4, 5, 6], k = 7

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is guaranteed to be rotated at some pivot.
  • -104 <= k <= 104

cpp

class Solution {
public:
    bool searchInARotatedSortedArrayII(vector<int> &nums, int k)  {
      
    }
};

java

class Solution {
    public boolean searchInARotatedSortedArrayII(int[] nums, int k) {
      
    }
}

python

class Solution:
    def searchInARotatedSortedArrayII(self, nums, k):

javascript

class Solution {
    searchInARotatedSortedArrayII(nums, k) {
       
    }
}

csharp

public class Solution {
    public bool searchInARotatedSortedArrayII(List<int> nums, int k)  {
      
    }
}

go

func searchInARotatedSortedArrayII(nums []int, k int) bool {
	//your code goes here
}
Stuck? Show a way to structure it+
  1. 01Check the middle for target.
  2. 02When low, middle, and high values are equal, shrink both boundaries.
  3. 03Otherwise identify a sorted half.
  4. 04Test whether target lies in that half.
  5. 05Continue until found or empty.

Reference answer

Then expect these follow-ups

  • Give an input that forces O(n) behavior.

    Tests: follow-up reasoning

  • How would you find the minimum with duplicates?

    Tests: follow-up reasoning

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question