↓Skip to main content
  1. LeetCode/

LeetCode 154: Find Minimum in Rotated Sorted Array II

·1 min· ·
LeetCode Hard 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: hard First Attempt: 2022-11-28

  • Submissions: Accepted (first try)

Approach
#

LC 153 plus duplicates (Binary Search). When nums[mid] == nums[r], as in [3, 3, 1, 3] and [3, 1, 3, 3], the break could be on either side, but dropping nums[r] cannot lose the minimum (nums[mid] equals it), so r -= 1.

My Solution
#

class Solution:
    def findMin(self, nums: List[int]) -> int:
        l, r = 0, len(nums) - 1
        while l < r:
            mid = (l + r) // 2
            if nums[mid] > nums[r]:
                l = mid + 1
            elif nums[mid] < nums[r]:
                r = mid
            else:
                r -= 1                               # 相等時只能縮一格
        return nums[l]

Complexity
#

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

Mistakes to Avoid
#

  • On equality r = mid is wrong; the minimum may lie between mid and r.

Interview Explanation
#

As before I compare the middle with the right end, but on equality the break could be anywhere; since the right end equals the middle, removing it loses nothing, so the right bound decreases by one. Worst case O(n).

Related

LeetCode 1337: The K Weakest Rows in a Matrix
·1 min
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 note: soldiers come first in each row, so binary search the first 0 for the count; sort by (count, row index) and take k
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 275: H-Index II
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 275 note: with sorted citations, find the first i where citations[i] >= n - i; the answer is n - i, in O(log n) with binary search
LeetCode 540: Single Element in a Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 540 note: before the single element every pair starts at an even index, so binary search whether nums[mid] equals nums[mid + 1] at an even mid
LeetCode 611: Valid Triangle Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Greedy
LeetCode 611 note: sort, fix the longest side k, and use two pointers for the shorter sides; when the sum is large enough every i in between works, adding j - i at once