Design a Skiplist without using any built-in libraries.
A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.
For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:
You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).
Skiplist() Initializes the object of the skiplist.
bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.
void add(int num) Inserts the value num into the SkipList.
bool erase(int num) Removes the value num from the Skiplist and returns true. If num does not exist in the Skiplist, do nothing and return false. If there exist multiple num values, removing any one of them is fine.
Note that duplicates may exist in the Skiplist, your code needs to handle this situation.
A Skiplist is a data structure that allows for fast insertion, deletion, and search by maintaining multiple layers of sorted linked lists. Each higher layer levels up randomly and contains a subset of the elements from the lower level, making searching operations more efficient by skipping over large numbers of elements at once.
⏰ Time complexity: The time complexity for search, add, and erase operations is O(log(n)) on average due to the probabilistic balancing. The worst-case time complexity is O(n), but this happens very rarely due to the random level mechanism.
🧺 Space complexity: O(n) where n is the number of elements in the Skiplist.