↓Skip to main content
  1. LeetCode/

LeetCode 81: Search in Rotated Sorted Array II

·2 mins· ·
LeetCode Medium Array Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-26

  • Submissions: Accepted → Wrong Answer ×8 → Accepted → Wrong Answer → Accepted ×2 → Wrong Answer ×3 → Accepted → Wrong Answer → Accepted

Approach
#

Decide which half is sorted as in LC 33, but now with duplicates (Binary Search). When nums[l] == nums[mid], as in [1, 1, 1, 3, 1], you cannot tell whether the left half is sorted, so move l right by one and retry. With all values equal this degrades to O(n).

My Attempts
#

This took 19 submissions in 2022, nearly all WAs:

  • At first the direction came only from nums[r] >= target / nums[l] <= target, without deciding which half is sorted: [2, 2, 3, 0], target = 3 returned False.
  • After adding the sorted-half check, nums[l] == nums[mid] went unhandled, so duplicates misidentified the sorted half: [1, 2, 3, 1, 1, 1, 1], target = 2 returned False.
  • One version returned nothing at the end, and one returned -1 instead of False.

Solution
#

class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        l, r = 0, len(nums) - 1
        while l <= r:
            mid = (l + r) // 2
            if nums[mid] == target:
                return True
            if nums[l] == nums[mid]:                     # 分不出哪一半有序
                l += 1
            elif nums[l] < nums[mid]:                    # 左半有序
                if nums[l] <= target < nums[mid]:
                    r = mid - 1
                else:
                    l = mid + 1
            else:                                        # 右半有序
                if nums[mid] < target <= nums[r]:
                    l = mid + 1
                else:
                    r = mid - 1
        return False

Complexity
#

Average O(log n), worst case O(n), space O(1).

Mistakes to Avoid
#

  • Duplicates make nums[l] == nums[mid] undecidable; shrink by one.

Interview Explanation
#

As without duplicates I decide which half is sorted, but when nums[l] equals nums[mid] I cannot tell and move the left bound by one. Average O(log n), O(n) when all values match.

Related

LeetCode 74: Search a 2D Matrix
·2 mins
LeetCode Medium Array Binary-Search Matrix
LeetCode 74 note: each row continues the previous one in sorted order, so binary search it as a 1-D array of length m × n, mapping mid to (mid // n, mid % n)
LeetCode 33: Search in Rotated Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 33 note: after rotation one side of mid is always sorted; check whether the target lies in it and search there, otherwise search the other side
LeetCode 34: Find First and Last Position of Element in Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 34 note: two lower bounds: the first position >= target, and the first position >= target + 1 minus one
LeetCode 75: Sort Colors
·2 mins
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 note: the Dutch flag, with 0s left of low and 2s right of high; after swapping a 2 to high, do not advance, since the swapped-in value is unchecked
LeetCode 78: Subsets
·1 min
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 78 note: each element is either taken or not; iteratively, each new number copies every existing subset with the number appended
LeetCode 79: Word Search
·3 mins
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 note: backtrack from every cell, matching the next character in four directions with visited cells marked temporarily and restored; prune early with character counts