Persistent Segment Tree
l values were not given directly in the question to force an online solution to the problem without changing the given order of the queries.
You should refer to the links given below, and solve similar problems to understand persistent segment trees.
In the solution, we maintain an array
pos which contains the rightmost occurrence of each element. The persistent segment tree’s
nth root contains the number of distinct elements in the range
[1,n]. Since the segment tree counts only the rightmost occurrence of each element, it allows us to safely split our queries.