Medium
You are given a circular array nums
and an array queries
.
For each query i
, you have to find the following:
queries[i]
and any other index j
in the circular array, where nums[j] == nums[queries[i]]
. If no such index exists, the answer for that query should be -1.Return an array answer
of the same size as queries
, where answer[i]
represents the result for query i
.
Example 1:
Input: nums = [1,3,1,4,1,3,2], queries = [0,3,5]
Output: [2,-1,3]
Explanation:
queries[0] = 0
is nums[0] = 1
. The nearest index with the same value is 2, and the distance between them is 2.queries[1] = 3
is nums[3] = 4
. No other index contains 4, so the result is -1.queries[2] = 5
is nums[5] = 3
. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: 5 -> 6 -> 0 -> 1
).Example 2:
Input: nums = [1,2,3,4], queries = [0,1,2,3]
Output: [-1,-1,-1,-1]
Explanation:
Each value in nums
is unique, so no index shares the same value as the queried element. This results in -1 for all queries.
Constraints:
1 <= queries.length <= nums.length <= 105
1 <= nums[i] <= 106
0 <= queries[i] < nums.length
import kotlin.math.abs
import kotlin.math.min
class Solution {
fun solveQueries(nums: IntArray, queries: IntArray): List<Int> {
val sz = nums.size
val indices: MutableMap<Int, MutableList<Int>> = HashMap<Int, MutableList<Int>>()
for (i in 0..<sz) {
indices.computeIfAbsent(nums[i]) { _: Int -> ArrayList<Int>() }.add(i)
}
for (arr in indices.values) {
val m = arr.size
if (m == 1) {
nums[arr[0]] = -1
continue
}
for (i in 0..<m) {
val j: Int = arr[i]
val f: Int = arr[(i + 1) % m]
val b: Int = arr[(i - 1 + m) % m]
val forward = min(((sz - j - 1) + f + 1), abs((j - f)))
val backward = min(abs((b - j)), (j + (sz - b)))
nums[j] = min(backward, forward)
}
}
val res: MutableList<Int> = ArrayList<Int>()
for (q in queries) {
res.add(nums[q])
}
return res
}
}