Find Minimum in Rotated Sorted Array II in C++


Suppose we have an array that is sorted, now that is rotated at some pivot. The pivot is not known before. We have to find the minimum element from that array. So if the array is like [4,5,5,5,6,8,2,3,4], then the minimum element is 2.

To solve this, we will follow these steps −

  • Define one method called search(), this takes arr, low and high

  • if low = high, then return arr[low]

  • mid := low + (high – low) / 2

  • ans := inf

  • if arr[low] < arr[mid], then ans := min of arr[low] and search(arr, mid, high)

  • otherwise when arr[high] > arr[mid], then ans := min of arr[mid] and search(arr, low, mid)

  • otherwise when arr[low] = arr[mid], then ans := min of arr[low] and search(arr, low + 1, high)

  • otherwise when arr[high] = arr[mid], then ans := min of arr[high] and search(arr, low, high - 1)

  • return ans

  • From the main method call solve(nums, 0, size of nums – 1)

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int search(vector <int>& arr, int low, int high){
      if(low == high){
         return arr[low];
      }
      int mid = low + (high - low) / 2;
      int ans = INT_MAX;
      if(arr[low] < arr[mid]){
         ans = min(arr[low], search(arr, mid, high));
      }
      else if (arr[high] > arr[mid]){
         ans = min(arr[mid], search(arr, low, mid));
      }
      else if(arr[low] == arr[mid]){
         ans = min(arr[low], search(arr, low + 1, high));
      }
      else if(arr[high] == arr[mid]){
         ans = min(arr[high], search(arr, low, high - 1));
      }
      return ans;
   }
   int findMin(vector<int>& nums) {
      return search(nums, 0, nums.size() - 1);
   }
};
main(){
   Solution ob;
   vector<int> v = {4,5,5,5,6,8,2,3,4};
   cout <<(ob.findMin(v));
}

Input

[4,5,5,5,6,8,2,3,4]

Output

2

Updated on: 26-May-2020

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements