Closest Equal Element Queries Problem
#3488
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3488.
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 indexjin the circular array, wherenums[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:
- Query 0: The element at queries[0] = 0 is nums[0] = 1. The nearest index with the same value is 2, and the distance between them is 2.
- Query 1: The element at queries[1] = 3 is nums[3] = 4. No other index contains 4, so the result is -1.
- Query 2: The element at 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 <= 10^51 <= nums[i] <= 10^60 <= queries[i] < nums.length
Solution
Approach: Two Passes over a Doubled Array
The array is circular, so imagine it written twice (length 2n). For every position i of the doubled array, compute d[i], the distance to the nearest equal value:
- Scan left to right with a hash map
lastof the latest position of each value. Ifxwas seen at positionj, thend[i] = min(d[i], i - j). - Scan right to left the same way with a map of the next position, using
next - i.
Positions i and i + n stand for the same element, so merge them: d[i] = min(d[i], d[i + n]). A distance of n or more means the only equal element found is the element itself (wrapped around), so the answer is -1. Otherwise the answer for a query q is d[q].
Complexity: O(n + q) time and O(n) extra space.
class Solution:
def solveQueries(self, nums: List[int], queries: List[int]) -> List[int]:
n = len(nums)
m = n << 1
d = [m] * m
left = {}
for i in range(m):
x = nums[i % n]
if x in left:
d[i] = min(d[i], i - left[x])
left[x] = i
right = {}
for i in range(m - 1, -1, -1):
x = nums[i % n]
if x in right:
d[i] = min(d[i], right[x] - i)
right[x] = i
for i in range(n):
d[i] = min(d[i], d[i + n])
return [-1 if d[i] >= n else d[i] for i in queries]