Search in a Rotated Array
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
nums is an ascending array of distinct integers that was cut at some unknown position with the front part moved to the
back (e.g. [0, 1, 2, 4, 5, 6, 7] may become [4, 5, 6, 7, 0, 1, 2]; it may also be uncut). For each targets[j], return its
index (0-based) in nums, or -1 if it is absent, in the same order as targets.
Examples
| nums | targets | result |
|---|---|---|
[4, 5, 6, 7, 0, 1, 2] | [0, 3] | [4, -1] |
[1] | [1, 0] | [0, -1] |
[30, 40, 50, 10, 20] | [10, 50, 20] | [3, 2, 4] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[], targets: int[]) → int[]
Constraints
-
nums.length - The values of
numsare distinct and form a rotated ascending array. -
targets.length -
nums[i],targets[j]
Expected complexity
- Time
- O((N + Q) log N)
- Space
- O(1)
Examples
| nums | targets | Expected |
|---|---|---|
[4,5,6,7,0,1,2] | [0,3] | [4,-1] |
[1] | [1,0] | [0,-1] |
[30,40,50,10,20] | [10,50,20] | [3,2,4] |
Hint
Hint
Binary search for the rotation point p (the minimum): values before it are greater than the last value, values from
it on are not. Then nums[p..n-1] and nums[0..p-1] are both sorted; binary search the one whose range can contain the
target. (A value-to-index hash map also passes, since the values are distinct.) A linear scan per target is
and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1618 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 3 | verdict only |