Skip to the code
+25 XP

#84 How Far Was It Rotated

medium

A ring buffer of timestamps was sorted ascending, with no repeats, and then rotated right by some unknown k (0 <= k < n) when it wrapped. You receive the rotated array nums.

Write rotationAmount(nums) that returns k. Use O(log n) time.

Example 1

Input: nums = [15,18,2,5,9]
Output: 2

The sorted array [2, 5, 9, 15, 18] rotated right by 2 gives this. The smallest value is at index 2.

Example 2

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

Already sorted, so it wasn't rotated.

Constraints

  • 1 <= nums.length <= 10^5
  • Values are distinct; -10^9 <= nums[i] <= 10^9.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).