logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›binary search›logic building

Find Minimum in Rotated Sorted Array

# Question

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. Given this rotated array nums of unique elements, return the minimum element of this array. The algorithm must run in O(log⁡n)O(\log n)O(logn) time.

# Solution

# Pattern

Binary Search (Pivot Identification via Right Boundary) In a rotated sorted array, the relationship between the mid element and the right element dictates exactly where the minimum lies. We use a while (left < right) template to squeeze the boundaries until they converge on the minimum.

# How to Identify

  • The array is explicitly stated to be sorted and rotated.
  • The problem requires O(log⁡N)O(\log N)O(logN) time, demanding binary search.
  • You are looking for the absolute minimum, which corresponds to the "pivot" point where the rotation wrapped the largest numbers to the left of the smallest numbers.

# Description

Step-by-step explanation:

  1. Initialize left = 0 and right = nums.length - 1.
  2. Loop strictly while left &lt; right. We do not use <= because we want the pointers to converge exactly on the answer.
  3. Calculate mid = left + (right - left) / 2 to avoid integer overflow.
  4. Compare nums[mid] against nums[right]. There are exactly two scenarios because all elements are unique:
    • Scenario A (nums[mid] &gt; nums[right]): The array from mid to right is "broken" or unsorted. Because the original array was ascending, a larger number appearing before a smaller number means the "wrap around" (the minimum) happened after mid. We discard the left half by setting left = mid + 1.
    • Scenario B (nums[mid] &lt; nums[right]): The array from mid to right is perfectly sorted. Because it is perfectly sorted, the minimum element in that specific range is nums[mid]. Therefore, the absolute minimum of the entire array must either be mid itself, or it is somewhere to the left of mid. We discard the right half by setting right = mid. (We do not do mid - 1 because mid is still a valid candidate).
  5. When the loop terminates, left will equal right, pointing precisely at the minimum element. Return nums[left].

# The Intuition

Imagine a broken clock face unrolled into a line. You expect numbers to go 1,2,3…121, 2, 3 \dots 121,2,3…12. Instead, because it's rotated, you see 9,10,11,12,1,2,39, 10, 11, 12, 1, 2, 39,10,11,12,1,2,3. You pick a random spot in the middle, say 121212. You look at the very end of the line, which is 333. Because 12 &gt; 3, you know the sequence "broke" and restarted somewhere between you and the end. The restart point (the minimum, 111) must be to your right. If instead you picked 222, and you look at the end and see 333. Because 2 &lt; 3, that section is perfectly normal. The break (the minimum) must have happened somewhere to your left, or you might actually be standing on it right now.

# Complexity

LabelWorstAverage
Time ComplexityO(log⁡N)O(\log N)O(logN)O(log⁡N)O(\log N)O(logN)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

The search space is halved in every iteration of the while loop. For an array of size NNN, this takes at most log⁡2(N)\log_2(N)log2​(N) iterations.

# Space Complexity

The algorithm operates entirely in place using only three integer variables (left, right, mid), requiring strictly O(1)O(1)O(1) auxiliary space.

# Code

class Solution {
    public int findMin(int[] nums) {
        if (nums == null || nums.length == 0) return -1;
 
        int left = 0;
        int right = nums.length - 1;
 
        // Loop until left and right converge on the single minimum element
        while (left < right) {
            int mid = left + (right - left) / 2;
 
            if (nums[mid] &gt; nums[right]) {
                // The right half is unsorted (it contains the pivot dip)
                // The minimum MUST be strictly to the right of mid
                left = mid + 1;
            } else {
                // The right half is perfectly sorted. 
                // The minimum could be mid itself, or somewhere to its left.
                right = mid;
            }
        }
 
        // When left == right, we have found the minimum
        return nums[left];
    }
}

# Caveats

  • Comparing to left instead of right: A common mistake is trying to compare nums[mid] to nums[left]. This logic fails when the array is not rotated (e.g., [1, 2, 3, 4]). In this case, nums[mid] &gt; nums[left] is true, which usually indicates the left is sorted and you should look right, but looking right skips the minimum (1). Comparing mid to right safely handles both rotated and perfectly sorted arrays.
  • while (left &lt;= right) Trap: If you use <= and right = mid - 1, the logic becomes incredibly convoluted because you might accidentally jump over the minimum element. The [left, right] convergence pattern (left < right with right = mid) is structurally superior for finding pivots.

# Concepts to Think About

  • Graphing the Array: If you plot the values of a rotated sorted array on a graph, it forms two distinct, parallel increasing lines. The minimum is simply the lowest point on the Y-axis. The condition nums[mid] &gt; nums[right] mathematically confirms that mid is on the higher line, and the right bound is on the lower line.
  • System Design Parity: This exact logic is useful for finding the newest/oldest entry in a circular buffer (ring buffer) where a head pointer has wrapped around.
  • Why compare to right and not left? If you compare mid to left, the "fully sorted" case (0 rotations) becomes an edge case you have to handle separately. Comparing to right handles both rotated and non-rotated arrays with the same logic.
  • The right = mid vs left = mid + 1 logic: When nums[mid]&lt;nums[right], mid could be the minimum itself, so we keep it. When nums[mid]&gt;nums[right], mid is definitely part of the "high" side, so we discard it.
  • Duplicates: If the array had duplicates, would this remain O(logn)? (No, we'd need to handle nums[mid]==nums[right] linearly).

# Logical Follow-up

Question: What if the array contains duplicate elements? (LeetCode 154: Find Minimum in Rotated Sorted Array II)

Solution: If duplicates exist, you can hit a scenario where nums[mid] == nums[right]. For example, [3, 3, 1, 3]. You cannot mathematically determine if the minimum is to the left or the right because the pivot could be trapped between identical values. In this case, you can only safely eliminate the rightmost element itself, because even if right was the minimum, mid shares the exact same value. You do right--. Because you shrink the window by 1, the worst-case time complexity degrades to O(N)O(N)O(N) (e.g., an array of all identical elements).

Question: "What happens if the array is rotated NNN times (making it effectively sorted)? Does your binary search logic still work, or does it return an incorrect index?"

Answer: It still works! If the array is sorted, nums[mid]nums[mid]nums[mid] will always be less than nums[right]nums[right]nums[right], causing the right pointer to move left until it reaches 0. The loop will terminate at left = 0, which is the correct minimum.

Question (Find the K-th Smallest Element): "You've successfully found the minimum element in O(log⁡n)O(\log n)O(logn). Now, can you find the k-th smallest element in the same rotated sorted array (distinct values) in O(1)O(1)O(1) additional time after finding the minimum?"

Answer:

  1. Find the Pivot: First, use the O(log⁡n)O(\log n)O(logn) algorithm above to find the index of the minimum element, let's call it pivot.
  2. Virtual Index Mapping: A rotated sorted array is just a regular sorted array that has been offset.
  3. The Formula: The kkk-th smallest element (000-indexed) in a sorted array is at index kkk. In a rotated array, that element is at: TargetIndex=(pivot+k)(modN)\text{TargetIndex} = (\text{pivot} + k) \pmod NTargetIndex=(pivot+k)(modN).
  4. Result: You return nums[TargetIndex].
PreviousCount Occurrences in a Sorted ArrayNextFind out how many times the array is rotated
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up