LC 153. Find Minimum in Rotated Sorted Array
- Last updated
- Reading time
- 2 min read
The problem
Time
First Solution -I solved this on the first try without help, but my solution was overly complex. Reflecting on this I have a simplified version below.
The main trick is to realize that the pointers can be shifted based on the relationship of mid and either of the ends of the array. I used both checked for both sides below which is redundant. My simplified solution just focuses on whether or not the right pointer is greater than or less than mid. If greater, right should be shifted below mid to locate the minimum. Otherwise, move left to mid + 1. Note that in my first attempt, I can move right to mid - 1 because my first if condition catches cases where mid is already the minimum. This can be eliminated completely though by moving right to mid instead of mid - 1, which I do in the concise version below.
function findMin(nums: number[]): number {
let left = 0
let right = nums.length - 1
while (left < right) {
const mid = Math.floor((right + left) / 2)
if (nums[mid - 1] > nums[mid] && nums[mid + 1] > nums[mid]) {
left = mid
right = mid
} else if (nums[mid] > nums[right] && nums[mid] >= nums[left]) {
left = mid + 1
} else {
right = mid - 1
}
}
return nums[left]
}
Simplified Solution
function findMin(nums: number[]): number {
let left = 0
let right = nums.length - 1
while (left < right) {
const mid = Math.floor((right + left) / 2)
if (nums[mid] > nums[right]) {
left = mid + 1
} else {
right = mid
}
}
return nums[left]
}