[LeetCode] Closest Equal Element Queries

3488. Closest Equal Element Queries

You are given a circular array nums and an array queries.

For each query i, you have to find the following:

  • The minimum distance between the element at index 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.

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
"math"
"sort"
)

func query(A []int, pos, n int) int {
if len(A) == 1 {
return -1
}

it := sort.Search(len(A), func(i int) bool { return A[i] >= pos })
res := math.MaxInt

fmt.Println(it)
if it != 0 {
res = min(res, pos-A[it-1])
} else {
res = min(res, n-A[len(A)-1]+pos)
}
if it != len(A) - 1 {
res = min(res, A[it+1]-pos)
} else {
res = min(res, n-pos+A[0])
}

return res
}

func solveQueries(nums []int, queries []int) []int {
at := make(map[int][]int)
for i, num := range nums {
at[num] = append(at[num], i)
}

res := make([]int, len(queries))
for i, q := range queries {
res[i] = query(at[nums[q]], q, len(nums))
}

return res
}

func min(a, b int) int {
if a < b {
return a
}
return b
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/16/PS/LeetCode/closest-equal-element-queries/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Related Issues not found

Please contact @SongHayoung to initialize the comment