1471. Self-Labelled Slot
A print shop numbers its trays from slot 0, and every tray carries a sticker holding one integer. The stickers in nums are strictly increasing from left to right, and some of them may be negative. A tray is called self-labelled when its sticker equals its own slot position, that is nums[i] == i.
Return the smallest slot index i that is self-labelled, or -1 if no tray qualifies. If several trays qualify, the lowest index must be returned.
Because the stickers are distinct integers in increasing order, nums[i] - i never decreases as i grows, which lets you halve the search range each step. Aim for O(log n) time and O(1) extra space.
Example 1
- Input:
- nums = [-4,-1,2,5,9]
- Output:
- 2
- Explanation:
Slot 2 holds sticker 2, and no earlier slot matches, so the answer is 2.
Example 2
- Input:
- nums = [1,3,8]
- Output:
- -1
- Explanation:
Every sticker is larger than its slot, so no tray is self-labelled and the answer is -1.
Example 3
- Input:
- nums = [0,4,9]
- Output:
- 0
- Explanation:
Slot 0 holds sticker 0, which is already the smallest possible index.
Constraints
1 ≤ nums.length ≤ 1000
-109 ≤ nums[i] ≤ 109
nums is strictly increasing
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(log n)
- Space
- O(1)