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

Search in Rotated Sorted Array

# Question

Given an integer array nums sorted in ascending order (with distinct values) that has been rotated at an unknown pivot index, and a target integer, return the index of target if it exists, or -1 if it does not. The algorithm must run in O(log⁡n)O(\log n)O(logn) time.

# Solution

# Pattern

Modified Binary Search (Sorted Half Identification) In any rotated sorted array, if you pick a middle index, at least one half of the array (either left to mid, or mid to right) is guaranteed to be perfectly sorted. Identify the sorted half, check if the target lies within its bounds, and discard half the search space accordingly.

# How to Identify

  • The problem specifies a sorted array that has been rotated or shifted.
  • The required time complexity is O(log⁡n)O(\log n)O(logn).
  • You are searching for a specific target value.

# Description

Step-by-step explanation:

  1. Initialize standard binary search pointers: left = 0, right = nums.length - 1.
  2. Loop while left <= right. Calculate mid safely.
  3. If nums[mid] == target, return mid.
  4. Identify the Sorted Half: Compare nums[left] and nums[mid].
    • If nums[left] <= nums[mid]: The left half [left, mid] is perfectly sorted without any pivot break.
      • Now, check if the target is within this sorted range: nums[left] <= target < nums[mid].
      • If it is, the target must be in this left half. Shrink the window: right = mid - 1.
      • If it isn't, the target must be in the right half. Shrink the window: left = mid + 1.
    • Else (nums[left] &gt; nums[mid]): The left half contains the pivot. Therefore, the right half [mid, right] must be perfectly sorted.
      • Check if the target is within this sorted range: nums[mid] &lt; target <= nums[right].
      • If it is, the target must be in this right half. Shrink the window: left = mid + 1.
      • If it isn't, the target must be in the left half. Shrink the window: right = mid - 1.
  5. If the loop breaks, the target was not found. Return -1.

# The Intuition

If you cut a deck of sorted cards exactly once (a rotation) and then split that deck roughly in half, one of those two halves will always be a perfectly continuous, sorted sequence. The pivot (the "break" in the sorting) will be trapped in the other half. Because it's very easy to check if a number belongs inside a perfectly sorted sequence (you just check if it's ≥\ge≥ the start and ≤\le≤ the end), we always evaluate the perfectly sorted half first. If the target fits nicely in the sorted half, we search there. If it doesn't fit, by process of elimination, it must be hiding in the messy, unsorted half.

# 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

At each step, we identify which half the target belongs in and completely discard the other half. The search space is halved every iteration, taking at most log⁡2(N)\log_2(N)log2​(N) iterations.

# Space Complexity

We only allocate three scalar pointers (left, right, mid), meaning the algorithm operates strictly in-place. Auxiliary space is O(1)O(1)O(1).

# Code

class Solution {
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) return -1;
 
        int left = 0, right = nums.length - 1;
 
        while (left <= right) {
            int mid = left + (right - left) / 2;
 
            if (nums[mid] == target) return mid;
 
            // Determine if the LEFT half is sorted
            if (nums[left] <= nums[mid]) {
                // Does target fall strictly within the sorted left bounds?
                if (target &gt;= nums[left] && target &lt; nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } 
            // Otherwise, the RIGHT half must be sorted
            else {
                // Does target fall strictly within the sorted right bounds?
                if (target &gt; nums[mid] && target &lt;= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
 
        return -1;
    }
}

# Caveats

  • The <= Operator Trap: In the condition if (nums[left] <= nums[mid]), the equals sign is mandatory. If the search window shrinks to size 2 (e.g., left = 0, right = 1), mid evaluates to 0. So nums[left] and nums[mid] point to the exact same element. If you only use <, the logic will falsely assume the left half is unsorted and jump to the else block, causing failures on small arrays or near the end of searches.
  • Two-Pass Alternative: You can also solve this by doing a binary search to find the index of the minimum element (the pivot), and then doing a second, normal binary search on the appropriate half of the array. This is also O(log⁡N)O(\log N)O(logN), but writing two separate binary search functions is longer and more prone to typos in an interview setting.

# Concepts to Think About

  • Finding the Minimum: You can use a similar logic just to find the smallest element (the pivot) in a rotated array (LeetCode 153). You compare nums[mid] with nums[right]. If nums[mid] &gt; nums[right], the minimum is in the right half. Otherwise, it's in the left half (including mid).
  • Duplicate Elements: If the array contains duplicates, this O(log⁡N)O(\log N)O(logN) algorithm breaks.
  • Strict Monotonicity: This logic relies on the values being distinct. If duplicates are introduced, the condition nums[left] == nums[mid] == nums[right] makes it impossible to know which side is sorted without a linear shrink (O(n)).
  • Pivot vs. Target: Finding the smallest element (the pivot) is a different problem. There, the predicate is nums[mid] > nums[right].
  • The "One-Pass" Advantage: While you could find the pivot first and then do a normal binary search, the one-pass approach is cleaner and more highly regarded in Google interviews.

# Logical Follow-up

Question: What if the array contains duplicate elements? (LeetCode 81: Search in Rotated Sorted Array II)

Solution: If there are duplicates, you might encounter a situation where nums[left] == nums[mid] == nums[right] (e.g., [3, 1, 2, 3, 3, 3, 3]). In this scenario, you cannot mathematically determine which half is perfectly sorted and which half contains the pivot. You must shrink the search space manually from both sides by doing left++ and right-- until the duplicates are resolved. Because you shrink by 1 step at a time in this worst-case scenario, the time complexity degrades to O(N)O(N)O(N).

Question: "What if the array is rotated but looks exactly like the original sorted array (rotated by nnn or 000 positions)? Does your logic change?"

Solution: No. The nums[left] <= nums[mid] condition will simply be true for every iteration, and the algorithm will behave like a standard binary search. This proves the robustness of the approach—it handles the "zero-rotation" case without needing a special if statement.

PreviousKth Missing Positive NumberNextSearch in Rotated Sorted Array II (With Duplicates)
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up