1480. Rotated Shelf Rank

Medium3.5 points estimatedBinary SearchArray

A library shelf holds books with distinct reference numbers. It was once arranged in strictly increasing order, but a cleaner lifted some books (possibly none) off the front and placed them at the back, so nums is a rotated copy of that sorted order and the rotation amount is unknown.

Given nums and an integer target (which may or may not appear in the array), return how many elements of nums are strictly less than target. Find the rotation point first, then run a lower-bound search inside each of the two sorted parts and add the two counts. Aim for O(log n) time and O(1) extra space.

Example 1

Input:
nums = [40,50,60,10,20,30], target = 35
Output:
3
Explanation:

The array is [10,20,30,40,50,60] rotated by three; 10, 20 and 30 are below 35.

Example 2

Input:
nums = [7,9,12,15], target = 12
Output:
2
Explanation:

No rotation here; only 7 and 9 are strictly below 12, and 12 itself is not counted.

Example 3

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

The sorted order is 1, 3, 5, so the two elements 1 and 3 are below 4.

Constraints

1 ≤ n ≤ 1000

-109 ≤ nums[i], target ≤ 109

All values of nums are distinct; nums is a rotation of a strictly increasing array.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(log n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…