Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding smallest element in a sorted array which is rotated in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the only argument.
The array is first sorted and then rotated by any arbitrary number of elements. Our function should find the smallest element in the array and return that element.
The only condition is that we have to do this in less than linear time complexity, using a modified binary search algorithm that achieves O(log n) time complexity.
Problem Understanding
In a rotated sorted array like [6, 8, 12, 25, 2, 4, 5], the original sorted array [2, 4, 5, 6, 8, 12, 25] was rotated. The smallest element (2) is at the rotation point.
Algorithm Approach
We use binary search to find the rotation point where the smallest element exists:
- Compare middle element with left and right boundaries
- Determine which half contains the rotation point
- Narrow search space accordingly
Example
If the input array is:
const arr = [6, 8, 12, 25, 2, 4, 5];
Then the output should be 2.
Implementation
const arr = [6, 8, 12, 25, 2, 4, 5];
const findMin = (arr = []) => {
let temp;
let min = 0;
let max = arr.length - 1;
let currentMin = Number.POSITIVE_INFINITY;
while (min <= max) {
temp = (min + max) >> 1;
currentMin = Math.min(currentMin, arr[temp]);
if (arr[min] < arr[temp] && arr[temp] <= arr[max] || arr[min] > arr[temp]) {
max = temp - 1;
} else if (arr[temp] === arr[min] && arr[min] === arr[max]) {
let guessNum = arr[temp];
while (min <= max && arr[min] === guessNum) {
min++;
}
} else {
min = temp + 1;
}
}
return currentMin;
};
console.log(findMin(arr));
Output
2
How It Works
The algorithm works by:
-
Binary Search: Calculate middle index using bit shifting
(min + max) >> 1 -
Track Minimum: Keep updating
currentMinwith the smallest element found - Determine Search Direction: Compare elements to decide which half to search next
- Handle Duplicates: Special case when all elements in current range are equal
Time Complexity
| Case | Time Complexity | Description |
|---|---|---|
| Best/Average | O(log n) | No duplicates, clear rotation point |
| Worst | O(n) | Many duplicates requiring linear scan |
Alternative Simpler Approach
const findMinSimple = (arr) => {
let left = 0, right = arr.length - 1;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] > arr[right]) {
left = mid + 1;
} else {
right = mid;
}
}
return arr[left];
};
console.log(findMinSimple([6, 8, 12, 25, 2, 4, 5]));
console.log(findMinSimple([4, 5, 6, 7, 0, 1, 2]));
2 0
Conclusion
Finding the minimum in a rotated sorted array uses modified binary search to achieve O(log n) complexity. The key insight is comparing the middle element with boundaries to determine the search direction.
