1483. Jostled Shelf Search
A shelf of distinct numbered boxes was sorted in ascending order, but a clumsy stacker then nudged some of them: every box in nums now sits at most one position away from the place it would occupy in the fully sorted shelf.
Given nums and an integer target, return the index where target is stored, or -1 if it is not on the shelf. Run a binary search that, at each middle position, compares target with the middle box and with both of its neighbours, and when none matches discards the range by moving the boundary two positions past the middle. The array is not guaranteed to be sorted, so a plain binary search is not enough. Aim for O(log n) time and O(1) extra space.
Example 1
- Input:
- nums = [10,30,20,40,60,50,70], target = 60
- Output:
- 4
- Explanation:
Sorted order is 10,20,30,40,50,60,70; 60 has drifted one place left of its sorted slot and sits at index 4.
Example 2
- Input:
- nums = [2,1,4,3], target = 3
- Output:
- 3
- Explanation:
Two neighbouring pairs are swapped; 3 ends up at index 3.
Example 3
- Input:
- nums = [5,8,12], target = 9
- Output:
- -1
- Explanation:
9 is not in the array, so the answer is -1.
Constraints
1 ≤ n ≤ 1000
-109 ≤ nums[i], target ≤ 109
All values are distinct; every element lies within one position of its index in sorted order.
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)