You are given an integer array nums and a range [l, r] of indices. Determine whether the elements nums[l], nums[l + 1], ..., nums[r] are all distinct, that is, whether no value appears twice in the range.
The interviewer then extended the task: many different ranges will be queried against the same array, so precompute information about nums once, with the best preprocessing time you can achieve, such that every query is answered in O(1) time. Implement the extended version, which receives all the queries at once.
Function Signature
def ranges_distinct(nums: list[int], queries: list[list[int]]) -> list[bool]:
Rules
-
Each query is
[l, r]
with 0-indexed, inclusive bounds.
-
The answer to a query is
True
if no value occurs more than once among
nums[l..r]
, and
False
otherwise. A range with one element is always
True
.
-
Return the answers in the order of
queries
.
-
The preprocessing may depend only on
nums
, and each query must then be answered in O(1) time.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
-
1 <= len(queries) <= 10^5
-
0 <= l <= r < len(nums)
for every query
Examples
Example 1
Input: nums = [3, 1, 4, 1, 5, 9, 2, 6, 5]
queries = [[0, 2], [0, 3], [4, 7], [2, 8], [5, 5]]
Output: [True, False, True, False, True]
nums[0..3] contains 1 twice (indices 1 and 3), and nums[2..8] contains 5 twice (indices 4 and 8). The other three ranges have no repeated value.
Example 2
Input: nums = [2, 2]
queries = [[0, 0], [0, 1], [1, 1]]
Output: [True, False, True]
Each single-element range is distinct, while the whole array repeats 2.