Idea
you can create a dict . For each element, a sorted list of positions where it occurs is stored.
To answer the query: the first element of a binary search that is greater than or equal to a , check if it exists and is less than b
pseudo code
Preprocessing:
from collections import defaultdict byvalue = defaultdict(list) for i, x in enumerate(data): byvalue[x].append(i)
Query:
def has_index_in_slice(indices, a, b): r = bisect.bisect_left(indices, a) return r < len(indices) and indices[r] < b def check(byvalue, x, a, b): indices = byvalue.get(x, None) if not indices: return False return has_index_in_slice(indices, a, b)
The complexity of O(log N) per query is here if we assume that list and dict have the difficulty of "getting by index" O (1).
source share