logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
2. Add Two Numbers3. Longest Substring Without Repeating Characters5. Longest Palindromic Substring8. String to Integer (atoi)11. Container With Most Water15. 3Sum17. Letter Combinations of a Phone Number19. Remove Nth Node From End of List22. Generate Parentheses33. Search in Rotated Sorted Array34. Find First and Last Position of Element in Sorted Array48. Rotate Image49. Group Anagrams50. Pow(x, n)53. Maximum Subarray54. Spiral Matrix56. Merge Intervals61. Rotate List73. Set Matrix Zeroes74. Search a 2D Matrix75. Sort Colors78. Subsets137. Single Number II138. Copy List with Random Pointer150. Evaluate Reverse Polish Notation151. Reverse Words in a String153. Find Minimum in Rotated Sorted Array155. Min Stack162. Find Peak Element169. Majority Element198. House Robber207. Course Schedule215. Kth Largest Element in an Array227. Basic Calculator II236. Lowest Common Ancestor of a Binary Tree237. Delete Node in a Linked List238. Product of Array Except Self451. Sort Characters By Frequency540. Single Element in a Sorted Array560. Subarray Sum Equals K636. Exclusive Time of Functions875. Koko Eating Bananas1011. Capacity To Ship Packages Within D Days1101. The Earliest Moment When Everyone Become Friends1283. Find the Smallest Divisor Given a Threshold2140. Solving Questions With Brainpower3169. Count Days Without Meetings3481. Apply Substitutions
Code Scratch/leetcode/medium

33. Search in Rotated Sorted Array

2 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

The input array is sorted but rotated at an unknown pivot. To search efficiently in O(log n)

  • We identify the pivot (i.e., the index of the largest element).
  • The array can be split into two sorted halves: from 0 to pivot and from pivot+1 to n-1.
  • Depending on the target, we perform binary search in the correct half.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(log⁡N)\text{O}(\log{N})O(logN)

# Code

// Helper method to find the index of the pivot (maximum element)
int findPivotIndex(int[] nums) {
    int left = 0, right = nums.length - 1;
 
    while (left <= right) {
        int mid = (left + right) >> 1;
 
        // Check if mid is the pivot (greater than both neighbors)
        boolean isGreaterThanLeft = (mid - 1 < 0 || nums[mid] > nums[mid - 1]);
        boolean isGreaterThanRight = (mid + 1 >= nums.length || nums[mid] > nums[mid + 1]);
 
        if (isGreaterThanLeft && isGreaterThanRight) {
            return mid;
        }
 
        // If mid is less than last element, pivot is on the left
        if (nums[mid] < nums[nums.length - 1]) {
            right = mid - 1;
        } else {
            left = mid + 1; // Pivot is on the right
        }
    }
 
    return -1; // Should never happen if array is rotated correctly
}
 
public int search(int[] nums, int target) {
    int resultIndex = -1;
 
    // Case 1: Array is not rotated (already sorted)
    if (nums[0] <= nums[nums.length - 1]) {
        resultIndex = Arrays.binarySearch(nums, target);
        return resultIndex < 0 ? -1 : resultIndex;
    }
 
    // Step 1: Find pivot index
    int pivotIndex = findPivotIndex(nums);
 
    // Step 2: Decide which half to search based on target
    if (target &gt;= nums[0] && target <= nums[pivotIndex]) {
        // Target is in the left sorted portion
        resultIndex = Arrays.binarySearch(nums, 0, pivotIndex + 1, target);
    } else {
        // Target is in the right sorted portion
        resultIndex = Arrays.binarySearch(nums, pivotIndex + 1, nums.length, target);
    }
 
    return resultIndex < 0 ? -1 : resultIndex;
}
 
←Previous22. Generate ParenthesesNext→34. Find First and Last Position of Element in Sorted Array

On this page

IntuitionComplexityCode