I’ve solved next task Find Minimum in Rotated Sorted ArrayII. The main difference between two solutions is duplication. So, task description:
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.
0 1 2 4 5 6 7might become
4 5 6 7 0 1 2).
Find the minimum element.
The array may contain duplicates.
OK, original algorithm:
[crayon-5bc5b90b9817c025635818/] We can see just two conditions middle more than right or not,
[crayon-5bc5b90b98187829615873/] OK, now we should handle one more condition, and yes, you are right equal ==. Generally we have to check if A[l] (left one) equals to A[m] (middle one) and equals to A[r] (right one) if yes, increase left index, or decrease right 🙂 and it would work. Yes, complexity will be O(N).
But what will be if we try to check recursively left and right part of array, if middle element equals to right one:
[crayon-5bc5b90b9818c780561236/] It should work and complexity should be better. OK, let’s go to implement this algorithm:
[crayon-5bc5b90b98190520910715/] We can see one additional condition and method. What is happening ? If middle element equals to right we try to recursively run into right side:
[crayon-5bc5b90b98195203742016/] and into left side
[crayon-5bc5b90b98198782459018/] after that just check what is bigger and return result. That is very good, but what is the complexity ? Of course we will have the same O(N), but actually twice faster, because real complexity will be O(N/2) but constants are ignoring in big O notation.
So, this is all leetcode accepted solution 🙂