oneby7

Binary Search Lower and upper bounds

231. How Many Times Is a Sorted Array Rotated

Medium

You are given an array nums of distinct integers. It was made by sorting some integers in increasing order and then rotating the sorted array some number of times, between 0 and nums.length − 1. Return the number of rotations.

Rotating an array once moves its last element to the front. For example, rotating [1, 3, 5, 7, 9] once gives [9, 1, 3, 5, 7], and rotating it twice gives [7, 9, 1, 3, 5].

Aim for O(log n) time.

Example 1

Input: nums = [27, 35, 48, -14, -6, 0, 9, 21]

Output: 3

Explanation: The sorted array [-14, -6, 0, 9, 21, 27, 35, 48] was rotated three times. Each rotation moved one of 48, 35 and 27 to the front, so the smallest value, −14, now sits at index 3.

Example 2

Input: nums = [-5, 2, 8, 19, 40]

Output: 0

Explanation: The array is still sorted, so it was rotated zero times.

Example 3

Input: nums = [-3, 7, 1000000000, -1000000000]

Output: 3

Explanation: The sorted array [-1000000000, -3, 7, 1000000000] was rotated three times, the most a 4-element array allows. Every value except the smallest moved to the front, so the smallest is now last.

Check your understanding

Work out the answer for this input before you write any code.

nums = [31, 44, 58, 70, 6, 12]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • All values in nums are distinct.
  • nums is an array sorted in increasing order and then rotated between 0 and nums.length − 1 times.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.