Talentd
FleetCode
Make and follow sheets.Sign in

Find Minimum in Rotated Sorted Array II solution and explanation

HardArrayBinary Search4 min read47.2% acceptanceUpdated 9 Apr 2026
Find Minimum in Rotated Sorted Array II & l | Leetcode 154 & 153 | HindiCodebix · 19:51 · 21K viewsWatch on YouTube
9 more videos on this problem
  1. Find Minimum in Rotated Sorted Array II & l | Leetcode 154 & 153 | HindiCodebix · 19:51 · 21K views
  2. Find Minimum in Rotated Sorted Array ii | LeetCode 154 | C++, Java, Python3Knowledge Center · 15:29 · 14K views
  3. Find Minimum in Rotated Sorted Array II | Simplified | Template | Dry Run | Leetcode 154 | MIKcodestorywithMIK · 20:57 · 6K views
  4. [Java] Leetcode 154. Find Minimum in Rotated Sorted Array II [Binary Search #2]Eric Programming · 6:08 · 4K views
  5. Find Minimum in Rotated Sorted Array II | Leetcode 154 | Live coding session 🔥🔥| Binary search AlgoCoding Decoded · 13:08 · 3K views
  6. Leetcode - Find Minimum in Rotated Sorted Array II (Python)Timothy H Chang · 4:35 · 2K views
  7. Find Minimum in Rotated Sorted Array II | Leet code 154 | Theory explained + Python codeSai Anish Malla · 11:50 · 1K views
  8. Leetcode 154. Find Minimum in Rotated Sorted Array | Optimal Complete Dry Run 🧙‍♂️🪄 | Video 10CodeWithKai · 16:12 · 391 views
  9. 154. Find Minimum in Rotated Sorted Array II | Leetcode Daily - PythonLeetcode Daily · 5:58 · 185 views
  10. Find Minimum in Rotated Sorted Array II | LeetCode 154 - Pythonimpoldev · 5:56 · 180 views

The problem

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:

  • [4,5,6,7,0,1,4] if it was rotated 4 times.
  • [0,1,4,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.

You must decrease the overall operation steps as much as possible.

Example 1:

Input: nums = [1,3,5]
Output: 1

Example 2:

Input: nums = [2,2,2,0,1]
Output: 0

Constraints:

  • n == nums.length
  • 1 <= n <= 5000
  • -5000 <= nums[i] <= 5000
  • nums is sorted and rotated between 1 and n times.

Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?

Approach overview

Problem Overview: You are given a sorted array that has been rotated at an unknown pivot and may contain duplicates. Your task is to return the smallest element in the array. The challenge is handling duplicates, which can break the strict ordering normally used by binary search.

Approach 1: Using Hash Maps for Optimal Time Complexity (O(n) time, O(n) space)

This approach scans the array once while storing visited values in a hash map or set-like structure. As you iterate through the array, track the smallest value seen so far. The hash map ensures constant-time lookups if you want to avoid redundant processing when duplicates appear, though the main work is still a single pass through the array. The key idea is simplicity: since duplicates make pivot detection tricky, a linear scan guarantees the correct minimum regardless of rotation. Prefer this method when constraints are small or when clarity is more important than logarithmic performance.

Approach 2: Using Sorted Arrays and Binary Search (O(log n) average time, O(1) space)

This method exploits the partially sorted structure of the rotated array. Maintain two pointers, left and right, and compute mid each iteration. If nums[mid] < nums[right], the minimum lies in the left half including mid. If nums[mid] > nums[right], the minimum must be in the right half, so move left = mid + 1. Duplicates create ambiguity when nums[mid] == nums[right]; in that case shrink the search space by decrementing right--. This preserves correctness but can degrade to O(n) in worst cases where many duplicates exist. Despite that edge case, the approach typically runs in logarithmic time and uses constant memory.

Recommended for interviews: The binary search solution is what most interviewers expect. It demonstrates understanding of rotated arrays and how duplicates affect search invariants in binary search. A linear scan or hash-based approach proves you can solve the problem correctly, but the optimized pointer-based search shows stronger algorithmic reasoning and space efficiency.

Approach 1: Approach 1: Using Hash Maps for Optimal Time Complexity

This approach utilizes hash maps (dictionaries in Python) to achieve optimal time and space complexity for operations such as insertion, deletion, and lookup. By storing elements as keys in a hash map, we benefit from average-case O(1) time complexity for these operations.

class MySet:
    def __init__(self):
        self._data = {}

    def insert(self, key):
        self._data[key] = True

    def search(self, key):
        return key in self._data

# Example usage
my_set = MySet()
my_set.insert(10)
print(my_set.search(10))  # Output: True
print(my_set.search(20))  # Output: False
import java.util.HashMap;

public class MySet {
    private HashMap<Integer, Boolean> hashMap;

    public MySet() {
        hashMap = new HashMap<>();
    }

    public void insert(int key) {
        hashMap.put(key, true);
    }

    public boolean search(int key) {
        return hashMap.containsKey(key);
    }

    public static void main(String[] args) {
        MySet mySet = new MySet();
        mySet.insert(10);
        System.out.println("Search for 10: " + mySet.search(10)); // Output: true
        System.out.println("Search for 20: " + mySet.search(20)); // Output: false
    }
}
#include <iostream>
#include <unordered_map>

class MySet {
    std::unordered_map<int, int> hashMap;

public:
    void insert(int key) {
        hashMap[key] = 1;
    }

    bool search(int key) {
        return hashMap.find(key) != hashMap.end();
    }
};

int main() {
    MySet mySet;
    mySet.insert(10);
    std::cout << "Search for 10: " << mySet.search(10) << std::endl; // Output: 1
    std::cout << "Search for 20: " << mySet.search(20) << std::endl; // Output: 0
    return 0;
}
class MySet {
    constructor() {
        this.data = {};
    }

    insert(key) {
        this.data[key] = true;
    }

    search(key) {
        return this.data.hasOwnProperty(key);
    }
}

const mySet = new MySet();
mySet.insert(10);
console.log("Search for 10: ", mySet.search(10)); // Output: true
console.log("Search for 20: ", mySet.search(20)); // Output: false
#include <stdio.h>
#include <stdlib.h>

#define TABLE_SIZE 1000

struct Node {
    int key;
    struct Node* next;
};

struct Node* hashTable[TABLE_SIZE];

int hashFunction(int key) {
    return key % TABLE_SIZE;
}

void insert(int key) {
    int index = hashFunction(key);
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->key = key;
    newNode->next = hashTable[index];
    hashTable[index] = newNode;
}

int search(int key) {
    int index = hashFunction(key);
    struct Node* head = hashTable[index];
    while (head != NULL) {
        if (head->key == key) return 1;
        head = head->next;
    }
    return 0;
}

int main() {
    insert(10);
    printf("Search for 10: %d\n", search(10)); // Output: 1
    printf("Search for 20: %d\n", search(20)); // Output: 0
    return 0;
}
using System;
using System.Collections.Generic;

class MySet {
    private Dictionary<int, bool> hashMap;

    public MySet() {
        hashMap = new Dictionary<int, bool>();
    }

    public void Insert(int key) {
        hashMap[key] = true;
    }

    public bool Search(int key) {
        return hashMap.ContainsKey(key);
    }

    static void Main() {
        MySet mySet = new MySet();
        mySet.Insert(10);
        Console.WriteLine("Search for 10: " + mySet.Search(10)); // Output: True
        Console.WriteLine("Search for 20: " + mySet.Search(20)); // Output: False
    }
}

Python's dictionaries serve as a direct means to emulate hash maps, where presence in the dictionary indicates inclusion in the set.

Complexity

Time Complexity: O(1) on average due to hash map performance.
Space Complexity: O(n).

Try this approach in the editor

Approach 2: Approach 2: Using Sorted Arrays and Binary Search

This approach leverages sorted arrays to perform efficient binary searches. Operations are optimized for scenarios requiring sorted data, such as when frequent minimum/maximum queries are performed.

import bisect

class MySet:
    def __init__(self):
        self.data = []

    def insert(self, key):
        bisect.insort_left(self.data, key)

    def search(self, key):
        index = bisect.bisect_left(self.data, key)
        return index < len(self.data) and self.data[index] == key

# Example usage
my_set = MySet()
my_set.insert(10)
print(my_set.search(10))  # Output: True
print(my_set.search(20))  # Output: False
import java.util.ArrayList;
import java.util.Collections;

public class MySet {
    private ArrayList<Integer> arr;

    public MySet() {
        arr = new ArrayList<>();
    }

    public void insert(int key) {
        arr.add(key);
        Collections.sort(arr);
    }

    public boolean search(int key) {
        return Collections.binarySearch(arr, key) >= 0;
    }

    public static void main(String[] args) {
        MySet mySet = new MySet();
        mySet.insert(10);
        System.out.println("Search for 10: " + mySet.search(10)); // Output: true
        System.out.println("Search for 20: " + mySet.search(20)); // Output: false
    }
}
#include <iostream>
#include <vector>
#include <algorithm>

class MySet {
    std::vector<int> arr;

public:
    void insert(int key) {
        arr.push_back(key);
        std::sort(arr.begin(), arr.end());
    }

    bool search(int key) {
        return std::binary_search(arr.begin(), arr.end(), key);
    }
};

int main() {
    MySet mySet;
    mySet.insert(10);
    std::cout << "Search for 10: " << mySet.search(10) << std::endl; // Output: 1
    std::cout << "Search for 20: " << mySet.search(20) << std::endl; // Output: 0
    return 0;
}
class MySet {
    constructor() {
        this.data = [];
    }

    insert(key) {
        if (!this.search(key)) {
            this.data.push(key);
            this.data.sort((a, b) => a - b);
        }
    }

    search(key) {
        let left = 0, right = this.data.length - 1;
        while (left <= right) {
            let mid = Math.floor((left + right) / 2);
            if (this.data[mid] === key) return true;
            if (this.data[mid] < key) left = mid + 1;
            else right = mid - 1;
        }
        return false;
    }
}

const mySet = new MySet();
mySet.insert(10);
console.log("Search for 10: ", mySet.search(10)); // Output: true
console.log("Search for 20: ", mySet.search(20)); // Output: false
#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

void insert(int arr[], int* size, int key) {
    arr[*size] = key;
    (*size)++;
    qsort(arr, *size, sizeof(int), compare);
}

int binarySearch(int arr[], int left, int right, int key) {
    if (right >= left) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == key) return 1;
        if (arr[mid] > key) return binarySearch(arr, left, mid - 1, key);
        return binarySearch(arr, mid + 1, right, key);
    }
    return 0;
}

int main() {
    int arr[100];
    int size = 0;
    insert(arr, &size, 10);
    printf("Search for 10: %d\n", binarySearch(arr, 0, size - 1, 10)); // Output: 1
    printf("Search for 20: %d\n", binarySearch(arr, 0, size - 1, 20)); // Output: 0
    return 0;
}
using System;
using System.Collections.Generic;

class MySet {
    private List<int> data;

    public MySet() {
        data = new List<int>();
    }

    public void Insert(int key) {
        int pos = data.BinarySearch(key);
        if (pos < 0) pos = ~pos;
        data.Insert(pos, key);
    }

    public bool Search(int key) {
        return data.BinarySearch(key) >= 0;
    }

    static void Main() {
        MySet mySet = new MySet();
        mySet.Insert(10);
        Console.WriteLine("Search for 10: " + mySet.Search(10)); // Output: True
        Console.WriteLine("Search for 20: " + mySet.Search(20)); // Output: False
    }
}

Python's bisect module provides efficient insertion (keeping the list sorted) and binary search capabilities, making it ideal for this approach.

Complexity

Time Complexity: O(n) insertion due to the move of elements and O(log n) for search.
Space Complexity: O(n).

Try this approach in the editor

Approach 3: Default Approach

function findMin(nums: number[]): number {
    let left = 0,
        right = nums.length - 1;
    while (left < right) {
        const mid = (left + right) >> 1;
        if (nums[mid] > nums[right]) {
            left = mid + 1;
        } else if (nums[mid] < nums[right]) {
            right = mid;
        } else {
            --right;
        }
    }
    return nums[left];
}
func findMin(nums []int) int {
	left, right := 0, len(nums)-1
	for left < right {
		mid := (left + right) >> 1
		if nums[mid] > nums[right] {
			left = mid + 1
		} else if nums[mid] < nums[right] {
			right = mid
		} else {
			right--
		}
	}
	return nums[left]
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Using Hash Maps for Optimal Time Complexity

Time Complexity: O(1) on average due to hash map performance.
Space Complexity: O(n).

Approach 2: Using Sorted Arrays and Binary Search

Time Complexity: O(n) insertion due to the move of elements and O(log n) for search.
Space Complexity: O(n).

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Hash Map / Linear ScanO(n)O(n)Simple implementation when constraints are small or duplicates make binary search logic unnecessary
Binary Search on Rotated ArrayO(log n) average, O(n) worstO(1)Preferred interview solution for rotated sorted arrays with duplicates

Frequently asked questions

Is Find Minimum in Rotated Sorted Array II easy or hard?

LeetCode classifies this problem as Hard because duplicates complicate the classic rotated-array binary search logic. Candidates must carefully maintain the search invariant and handle cases where comparisons do not clearly identify the sorted half.

Find Minimum in Rotated Sorted Array II Python/Java solution

Python and Java implementations typically follow the same binary search template: maintain left and right pointers, compute mid, compare nums[mid] with nums[right], and adjust the search range accordingly. Handle duplicates by reducing the right boundary when both values are equal.

How to solve Find Minimum in Rotated Sorted Array II in O(n)?

A straightforward solution iterates through the array and keeps track of the smallest value encountered. This linear scan guarantees correctness even with duplicates and rotations. The algorithm runs in O(n) time and uses O(1) or O(n) space depending on whether auxiliary structures like hash maps are used.

What is the best approach for Find Minimum in Rotated Sorted Array II?

Binary search with two pointers is the most efficient approach. Compare the middle element with the right boundary to decide which half contains the minimum. When duplicates make the comparison ambiguous, shrink the search space by decrementing the right pointer. This gives O(log n) average time and O(1) space.

Is Find Minimum in Rotated Sorted Array II asked at Google/Amazon/Meta?

Rotated array and binary search variations appear frequently in interviews at companies like Amazon, Google, Meta, and Microsoft. This specific problem tests whether candidates can adjust binary search logic when duplicates break strict ordering conditions.

What data structure is used in Find Minimum in Rotated Sorted Array II?

The problem primarily uses arrays combined with binary search techniques. Some simpler solutions may also use hash maps or sets to track visited values, but the optimal approach relies on pointer manipulation within the array itself.

What is the time complexity of Find Minimum in Rotated Sorted Array II?

The optimized binary search solution runs in O(log n) average time and O(1) space. However, when many duplicate values exist, the algorithm may shrink the search range one step at a time, degrading to O(n) in the worst case.

Comments

Now write it yourselfClose this page and solve Find Minimum in Rotated Sorted Array II in the editor, without looking.
Practise Find Minimum in Rotated Sorted Array II