2

If I have an incoming stream of integers how can I best maintain a sorted list of them? The only way I can think of is to binary search for the position and shifting the remaining elements to the right. This would amount to $O(N + \log N)$ time. Is there a better data structure that can help me achieve the same in better time? I know we can use a Balanced Binary Search Tree with $O(\log N)$ insertions but I would like to have efficient access on the list.

Andrew Scott
  • 153
  • 1
  • 5

1 Answers1

6

A balanced binary search tree can support access to arbitrary elements in $O(\log N)$ time per access. Augment the data structure to store, in each node, the number of values stored in the subtree under that node. Then you can find the $i$th largest value in the list in $O(\log N)$ time as well; thus, all basic operations can be done in $O(\log N)$ time.

D.W.
  • 167,959
  • 22
  • 232
  • 500