Find Minimum in Rotated Sorted Array II

Follow up for “Find Minimum in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

The array may contain duplicates.

Solution:

  1. public class Solution {
  2. public int findMin(int[] a) {
  3. return search(a, 0, a.length - 1);
  4. }
  5. int search(int[] a, int lo, int hi) {
  6. // a[] is sorted
  7. if (lo > hi) {
  8. return a[0];
  9. }
  10. int mid = lo + (hi - lo) / 2;
  11. if (mid > 0 && a[mid - 1] > a[mid]) {
  12. return a[mid];
  13. }
  14. if (mid < a.length - 1 && a[mid] > a[mid + 1]) {
  15. return a[mid + 1];
  16. }
  17. if (a[lo] == a[mid] && a[mid] == a[hi]) {
  18. return Math.min(search(a, lo, mid - 1), search(a, mid + 1, hi));
  19. }
  20. if (a[lo] <= a[mid]) {
  21. return search(a, mid + 1, hi);
  22. } else {
  23. return search(a, lo, mid - 1);
  24. }
  25. }
  26. }