Given an integer array nums of size N, sorted in ascending order with distinct values, and then rotated an unknown number of times (between 1 and N), find the minimum element in the array.
Input : nums = [4, 5, 6, 7, 0, 1, 2, 3]
Output: 0
Explanation: Here, the element 0 is the minimum element in the array.
Input : nums = [3, 4, 5, 1, 2]
Output: 1
Explanation:Here, the element 1 is the minimum element in the array.
Input : nums = [4, 5, 6, 7, -7, 1, 2, 3]
The idea here is to use simple linear search to fnd out the minimum element among the array elements.
mini
to INT_MAX, which is the maximum possible value for integers. This ensures that any element in the array will be smaller than mini initially.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to find minimum element in a vector
int findMin(vector<int>& arr) {
int n = arr.size();
// Initialize mini to maximum integer value
int mini = INT_MAX;
for (int i = 0; i < n; i++) {
/* Update mini with the
smaller of mini and arr[i]*/
mini = min(mini, arr[i]);
}
// Return the minimum element found
return mini;
}
};
int main() {
vector<int> arr = {4, 5, 6, 7, 0, 1, 2, 3};
// Create an object of the Solution class
Solution sol;
int ans = sol.findMin(arr);
//Print the result
cout << "The minimum element is: " << ans << "\n";
return 0;
}
import java.util.*;
class Solution {
// Function to find minimum element in an array
public int findMin(ArrayList<Integer> arr) {
// Initialize mini to maximum integer value
int mini = Integer.MAX_VALUE;
for (int i = 0; i < arr.size(); i++) {
/* Update mini with the
smaller of mini and arr[i]*/
mini = Math.min(mini, arr.get(i));
}
// Return the minimum element found
return mini;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(4, 5, 6, 7, 0, 1, 2, 3));
// Create an object of the Solution class
Solution sol = new Solution();
int ans = sol.findMin(arr);
// Print the result
System.out.println("The minimum element is: " + ans);
}
}
class Solution:
# Function to find minimum element in a list
def findMin(self, arr):
# Initialize mini to maximum float value
mini = float('inf')
for num in arr:
""" Update mini with the
smaller of mini and num"""
mini = min(mini, num)
# Return the minimum element found
return mini
if __name__ == "__main__":
arr = [4, 5, 6, 7, 0, 1, 2, 3]
# Create an object of the Solution class
sol = Solution()
ans = sol.findMin(arr)
# Print the result
print("The minimum element is:", ans)
class Solution {
// Function to find minimum element in an array
findMin(arr) {
// Initialize mini to maximum infinity value
let mini = Infinity;
for (let num of arr) {
/* Update mini with the
smaller of mini and num*/
mini = Math.min(mini, num);
}
// Return the minimum element found
return mini;
}
}
let arr = [4, 5, 6, 7, 0, 1, 2, 3];
// Create an object of the Solution class
let sol = new Solution();
let ans = sol.findMin(arr);
// Print the result
console.log("The minimum element is:", ans);
As the given array is sorted and then rotated, we can optimize the brute-force solution by applying the binary search algorithm. In any sorted array, the minimum element is located at the very first index. This observation allows us to reduce the search space by half in each iteration. The task is to identify the sorted half of the array, store its minimum element (which is the first element of this half), and then eliminate this half from our search space.
low
to 0 and high to sizeOfArray - 1, which represent the indices of the array arr that define the current search range, ans
to Integer.MAX_VALUE, which ensures that any element in the array will be smaller than ans initially.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find minimum element
in a rotated sorted array */
int findMin(vector<int>& arr) {
// Initialize low and high indices
int low = 0, high = arr.size() - 1;
// Initialize ans to maximum integer value
int ans = INT_MAX;
while (low <= high) {
int mid = (low + high) / 2;
// Check if left part is sorted
if (arr[low] <= arr[mid]) {
/* Update ans with minimum
of ans and arr[low] */
ans = min(ans, arr[low]);
// Move to the right part
low = mid + 1;
}
else {
/* Update ans with minimum
of ans and arr[mid] */
ans = min(ans, arr[mid]);
// Move to the left part
high = mid - 1;
}
}
// Return the minimum element found
return ans;
}
};
int main() {
vector<int> arr = {4, 5, 6, 7, 0, 1, 2, 3};
// Create an object of the Solution class
Solution sol;
int ans = sol.findMin(arr);
// Print the result
cout << "The minimum element is: " << ans << "\n";
return 0;
}
import java.util.*;
class Solution {
/* Function to find minimum element
in a rotated sorted array */
public int findMin(ArrayList<Integer> arr) {
// Initialize low and high indices
int low = 0, high = arr.size() - 1;
// Initialize ans to maximum integer value
int ans = Integer.MAX_VALUE;
while (low <= high) {
int mid = (low + high) / 2;
// Check if left part is sorted
if (arr.get(low) <= arr.get(mid)) {
/* Update ans with minimum
of ans and arr[low] */
ans = Math.min(ans, arr.get(low));
// Move to the right part
low = mid + 1;
} else {
/* Update ans with minimum
of ans and arr[mid] */
ans = Math.min(ans, arr.get(mid));
// Move to the left part
high = mid - 1;
}
}
// Return the minimum element found
return ans;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(4, 5, 6, 7, 0, 1, 2, 3));
//Create an instance of the Solution class
Solution sol = new Solution();
int ans = sol.findMin(arr);
System.out.println("The minimum element is: " + ans);
}
}
class Solution:
""" Function to find minimum element
in a rotated sorted array """
def findMin(self, arr):
# Initialize low and high indices
low, high = 0, len(arr) - 1
# Initialize ans to maximum integer value
ans = float('inf')
while low <= high:
mid = (low + high) // 2
# Check if left part is sorted
if arr[low] <= arr[mid]:
""" Update ans with minimum
of ans and arr[low] """
ans = min(ans, arr[low])
# Move to the right part
low = mid + 1
else:
""" Update ans with minimum
of ans and arr[mid] """
ans = min(ans, arr[mid])
# Move to the left part
high = mid - 1
# Return the minimum element found
return ans
if __name__ == "__main__":
arr = [4, 5, 6, 7, 0, 1, 2, 3]
#Create an instance of the Solution class
sol = Solution()
ans = sol.findMin(arr)
print("The minimum element is:", ans)
class Solution {
/* Function to find minimum element
in a rotated sorted array */
findMin(arr) {
// Initialize low and high indices
let low = 0, high = arr.length - 1;
// Initialize ans to maximum integer value
let ans = Infinity;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
// Check if left part is sorted
if (arr[low] <= arr[mid]) {
/* Update ans with minimum
of ans and arr[low] */
ans = Math.min(ans, arr[low]);
// Move to the right part
low = mid + 1;
} else {
/* Update ans with minimum
of ans and arr[mid] */
ans = Math.min(ans, arr[mid]);
// Move to the left part
high = mid - 1;
}
}
// Return the minimum element found
return ans;
}
}
let arr = [4, 5, 6, 7, 0, 1, 2, 3];
//Create an instance of the Solution class
let sol = new Solution();
let ans = sol.findMin(arr);
console.log("The minimum element is:", ans);
Q: What happens if the array is not rotated?
A: If the array is sorted and not rotated, the first element (nums[0]) is the minimum. This is detected in O(1) by checking if nums[low] <= nums[high] at the start of the binary search.
Q: How is the search space reduced at each step?
A: If nums[mid] > nums[high], the minimum cannot lie in the left half because all elements in the left half are greater than nums[mid]. Move low = mid + 1. If nums[mid] <= nums[high], the minimum could lie in the left half, so adjust high = mid.
Q: How would you find the index of the minimum element?
A: The algorithm remains the same, but instead of returning the element (nums[low]), return the index (low). This is particularly useful in applications like finding the rotation count.
Q: How would you detect if the array is rotated and not sorted?
A: Check if nums[0] <= nums[N-1]: If true, the array is sorted and not rotated. If false, the array is rotated.