Problem 336587 · medium · Level 03 Linear Management & Searching

How Many Times Was It Rotated?

binary search · rotated arrays

A sorted list of distinct integers was rotated to the right k times (each rotation moves the last element to the front). Given the rotated list nums, return k, where 0 <= k < len(nums).

Examples

Input:  nums = [4, 5, 1, 2, 3]
Output: 2
Explanation: [1, 2, 3, 4, 5] rotated right twice.

Input:  nums = [1, 2, 3, 4, 5]
Output: 0

Input:  nums = [5, 1, 2, 3, 4]
Output: 1

Constraints

  • 1 <= len(nums) <= 10**6
  • All values are distinct.
  • O(log n) time is required.

Goals

  • Compare against the last element to decide which half holds the minimum
  • Handle the unrotated case
Starting Python…