Solving LeetCode 33 - Search in Rotated Sorted Array in O(log n) time

This title was summarized by AI from the post below.

Binary search on a sorted array is easy. Binary search on a rotated sorted array is where it gets interesting. Day 36 of #100DaysOfCode Today I solved LeetCode 33 - Search in Rotated Sorted Array, and this is one of those problems that every developer preparing for interviews must know. The problem: A sorted array has been rotated at some unknown pivot. Given a target, find its index in O(log n) time or return -1. How I approached it: The key observation is that even after rotation, at least one half of the array is always perfectly sorted. I used this fact to decide which half to search. At every step I calculated mid and checked two things. First, if nums[low] <= nums[mid], the left half is sorted. In that case if target lies within nums[low] and nums[mid], I searched left, otherwise I moved to the right half. If the left half is not sorted, the right half must be sorted. Then if target lies within nums[mid] and nums[high], I searched right, otherwise I moved to the left half. This gives a clean O(log n) solution with no extra space. What I learned from this problem: The real insight here is not binary search itself, it is knowing which half is still sorted at every step. Once you identify the sorted half, the rest of the logic is exactly like standard binary search. This problem teaches you to extract useful information from partial structure in data, which is a skill that goes far beyond just this one problem. 0ms runtime beating 100% was a great result today. #100DaysOfCode #LeetCode #DSA #Java #BinarySearch #Programming #SoftwareEngineering #CodingChallenge #InterviewPrep

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories