Skip to content
BytePatterns

Count the Rotations

MediumSearching#binary-search#boundary-search~20m

Problem

A list of distinct numbers was sorted in increasing order and then rotated to the right r times, where one rotation moves the last element to the front and r is smaller than the list length. Given the rotated list, return r. The list has at least one element, and the answer should take O(log n) time.

Examples

Input:  nums = [15, 18, 2, 3, 6, 12]
Output: 2
Why:    the smallest value, 2, was carried two places to the right
Input:  nums = [1, 2, 3, 4]
Output: 0
Why:    the list was never rotated
Input:  nums = [9]
Output: 0
Why:    edge case, one element cannot move

Hints

0 / 3

Stuck on the idea rather than the code? Search in Rotated Array covers it.