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-5ba8933c0de66558452908/] We can see just two conditions middle more than right or not,
[crayon-5ba8933c0de70939482216/] 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-5ba8933c0de74114866871/] It should work and complexity should be better. OK, let’s go to implement this algorithm:
[crayon-5ba8933c0de78377580680/] 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-5ba8933c0de7c060959312/] and into left side
[crayon-5ba8933c0de7f294823854/] 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 🙂