Sunday, February 21, 2016

Compress Number List II - AlgoBox by dietpepsi

Compress Number List II – AlgoBox by dietpepsi
Given a stream of positive integers, design a data structure supporting two operations:
1. void insert(int x) insert an element.
2. String toString() print out the integers in a compressed format.
The compressed format is like this, for example:
Given [8, 6, 4, 7]
Return "4, 6-8"

Method 1: BST

Using a balanced BST we could perform insertion, deletion and search in time. The difference is for this problem we need to maintain intervals rather than numbers.
The trick is to use the start point as key and endpoint as value.