Skip to content

Improvement in time complexity of rotatedDistance problem(rotated sorted array) #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Akhilj786 opened this issue Sep 7, 2015 · 1 comment

Comments

@Akhilj786
Copy link

I came across 2 problem in your approach:

  1. If you are doing it O(n) then you could do a simple scan and just minimum value and then return its index. This could have avoided your complex code.
  2. Time complexity is O(log n):
    http://stackoverflow.com/questions/2796413/binary-search-to-find-the-rotation-point-in-a-rotated-sorted-list
@gbrand-salesforce
Copy link

gbrand-salesforce commented Mar 23, 2017

Also, this is more of a C code than C++.

The proper C++ solution would consist of a function with 2 lines:

template<typename ForewardIterator>
int get_rotation_dist(ForewardIterator first, ForewardIterator last)
{
    ForewardIterator itr = std::min_element(first, last);
    return std::min(std::distance(first, itr), std::distance(itr, last));
}

While this could be more efficient in runtime as per @Akhilj786 comment, it's much more readable and generic this way (works on all containers) and works the case of duplicate values in the rotated container (as opposed to the O(log n)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants