Is it possible to query number of distinct integers in a range in O(lg N)?

后端 未结 5 1420
滥情空心
滥情空心 2020-12-13 15:02

I have read through some tutorials about two common data structure which can achieve range update and query in O(lg N): Segment tree and Binary Indexed Tree (BIT / Fenwick T

5条回答
  •  醉话见心
    2020-12-13 15:21

    If you're willing to answer queries offline, then plain old Segment Trees/ BIT can still help.

    • Sort queries based on r values.
    • Make a Segment Tree for range sum queries [0, n]
    • For each value in input array from left to right:

      1. Increment by 1 at current index i in the segment tree.
      2. For current element, if it's been seen before, decrement by 1 in
        segment tree at it's previous position.

      3. Answer queries ending at current index i, by querying for sum in range [l, r == i].

    The idea in short is to keep marking rightward indexes, the latest occurrence of each individual element, and setting previous occurrences back to 0. The sum of range would give the count of unique elements.

    Overall time complexity again would be nLogn.

提交回复
热议问题