Suppose we have a sorted set (for example, a balanced binary search tree or skip list ) with N elements. Also, suppose the sorted set has O (log N) search time, O (log N) insertion time, and O (N) space usage (these are reasonable assumptions, see red-black tree , for example).
One possibility is to have two sorted sets, bystart and byend , respectively sorted by the start and end time of the events.
To find the number of events that flow at time t , ask byend for the first interval whose end time is longer than t : a search operation O (log N). Call the start time of this left interval. Now ask bystart number of intervals whose start time is greater than or equal to left and less than t . This is O (log N + M), where M is the number of such intervals. So, the total search time is O (log N + M).
The insert was O (log N) for the sorted sets, which we have to do once for each sorted set. This makes the total time for the insert operation O (log N).
The construction of this structure from scratch consists of only N insert operations, so the total time to build is O (N log N).
The use of space is O (N) for each sorted set, so the total use of space is O (N).
Summary:
- Insert: O (log N), where N is the number of intervals
- Construction: O (N log N)
- Query: O (log N + M), where M is the number of results
- Space: O (N)
Snowball
source share