Find Minimum in Rotated Sorted Array - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Goal

Given a rotated sorted array of unique integers, find the minimum element. The array is originally sorted in increasing order and then rotated.

Key Idea (Intuition)

The array can be divided into two sorted parts: a first half where all values are greater than those in the second half and is strictly increasing, and a second half that starts with the minimum element and is strictly increasing.
If there is no rotation, the size of the first half is 0 (the array is fully increasing).
By comparing nums[mid] with nums[right], we can determine which half mid belongs to and shrink the search space accordingly.

Binary Search Process

Initialize left = 0 and right = n - 1. While left < right:

  • If nums[mid] > nums[right], then mid must be in the first half (the larger part), since nums[right] is the greatest element in the second half. The minimum will always be in the second half, so it must be laying in the right side of mid. 👉 Move search to the right: left = mid + 1.
  • If nums[mid] ≤ nums[right], then mid lies in the second half (the smaller part), because every element in the first half is greater than any element in the second half, and nums[right] belongs to the second half. In this half, values are increasing and nums[right] is the maximum. The minimum is at the beginning of this half, so it must be either mid itself or somewhere to its left. 👉 Move search to the left side of this half: right = mid.

Termination

When the loop ends, left == right, both pointing to the index of the smallest element in the array. This element is the start of the second increasing section and is the minimum value in the entire array.

Time Complexity

The binary search halves the search interval each iteration and does only constant work per step (compute mid, compare with nums[right], and move one pointer). Therefore, the time complexity is O(log n).

Space Complexity

The algorithm only uses a constant number of variables (left, right, mid) and does not allocate any extra data structures. Therefore, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's Find Minimum in Rotated Sorted Array coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/find-minimum-in-rotated-sorted-array.