Closest Repeat Distance with Fast Threshold Queries
Data Structure DesignAuto-graded · 21 test casesLast updated
Precompute the smallest distance between equal values in an array once, then answer many "repeat within k" and "closest repeat" queries in constant time each.
Closest Repeat Queries
You are given an integer array nums that never changes, together with a list of queries to run against it. Because many queries are issued against the same array, the array should be analysed once, and each query should then be answered in constant time.
Two positions i and j form a repeat pair if i != j and nums[i] == nums[j]. The gap of such a pair is abs(i - j).
Query types
Each query is identified by a name in operations, with its parameters in the matching entry of arguments:
"min_gap"(arguments: an empty list): return the smallest gap over all repeat pairs innums. If no value occurs more than once, return-1."has_duplicate_within"(arguments:[k]): returntrueif at least one repeat pair has gap less than or equal tok, otherwisefalse. If the array has no repeat pair, the answer isfalsefor everyk. Akof0or less always yieldsfalse, since every real gap is at least 1.
Function
Implement closest_repeat_queries(nums, operations, arguments). It returns a list with one result per query, in the same order as operations. operations[t] pairs with arguments[t]. Integer results are returned for "min_gap" and booleans for "has_duplicate_within".
Any operation name other than the two above should raise a ValueError.
Constraints
1 <= len(nums), and the array can be large (on the order of10^5elements).- Elements of
numsare integers. len(operations) == len(arguments), and there can be up to about10^5queries.kis an integer and may be zero, negative, or larger than the array length.- Preprocessing should take
O(n)expected time and at mostO(n)extra space; each query should takeO(1)time.
Examples
Example 1
Input: closest_repeat_queries([1, 2, 3, 1, 2, 3], ['min_gap', 'has_duplicate_within', 'has_duplicate_within', 'has_duplicate_within'], [[], [2], [3], [5]])
Output: [3, False, True, True]
Example 2
Input: closest_repeat_queries([10, 20, 30, 40], ['min_gap', 'has_duplicate_within'], [[], [10]])
Output: [-1, False]
Example 3
Input: closest_repeat_queries([7, 7, 7, 8, 9, 8], ['has_duplicate_within', 'min_gap', 'has_duplicate_within', 'has_duplicate_within'], [[0], [], [1], [2]])
Output: [False, 1, True, True]
Hints
Hint 1
Whether a repeat pair with gap at most k exists depends on a single number: the smallest gap between any two equal values. Compute it once.
Hint 2
You do not need to compare all pairs. For each value, it is enough to compare each occurrence with the previous occurrence of the same value, so a dictionary from value to latest index suffices.
Hint 3
Keep the 'no repeats' case separate from real gaps (for example with None). Reporting -1 for min_gap is fine, but do not compare that -1 against k.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every query depends on one number: the smallest gap between two equal values, call it best.
min_gapreturnsbest, or-1when no value repeats.has_duplicate_within(k)is true exactly when a repeat pair with gap<= kexists. That is the same as sayingbestexists andbest <= k. Because the answer only depends on the minimum, it is monotone ink.
So the work is to compute best once, in a single pass:
- Keep a dictionary
last_indexmapping each value to the most recent index where it appeared. - At index
iwith valuev, ifvis already in the dictionary, the candidate gap isi - last_index[v]. Updatebestif it is smaller. - Set
last_index[v] = i.
Then answer each query by reading best.
Why it is correct
Only consecutive occurrences of a value need to be examined. Take any repeat pair (i, j) with i < j and value v. If v also appears at positions in between, say i = p0 < p1 < ... < pm = j, then each consecutive gap p(t+1) - p(t) is at most j - i. So the closest pair for any value is always a consecutive pair, and overwriting last_index never discards a better candidate.
The "no repeats" case is stored as None rather than -1, so that -1 <= k is never evaluated by mistake. Real gaps are at least 1, so k <= 0 naturally gives false.
Complexity
- Preprocessing:
O(n)expected time (hash map),O(d)extra space whered <= nis the number of distinct values. - Each query:
O(1)time and space. - Total:
O(n + q)forqqueries, instead ofO(n * q)if each query rescanned the array.
Reference solution
from typing import List, Optional
def closest_repeat_queries(nums: List[int], operations: List[str], arguments: List[List[int]]) -> List[Optional[object]]:
last_index = {}
best = None # None means no repeated value exists
for i, value in enumerate(nums):
if value in last_index:
gap = i - last_index[value]
if best is None or gap < best:
best = gap
last_index[value] = i
results = []
for operation, args in zip(operations, arguments):
if operation == "min_gap":
results.append(-1 if best is None else best)
elif operation == "has_duplicate_within":
k = args[0]
results.append(best is not None and best <= k)
else:
raise ValueError("unknown operation")
return results