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.
At most 5 * 104 calls will be made to search, add, and erase.
Solutions
Solution 1: Data Structure
The core idea of a skip list is to use multiple "levels" to store data, with each level acting as an index. Data starts from the bottom level linked list and gradually rises to higher levels, eventually forming a multi-level linked list structure. Each level's nodes only contain part of the data, allowing for jumps to reduce search time.
In this problem, we use a \(\textit{Node}\) class to represent the nodes of the skip list. Each node contains a \(\textit{val}\) field and a \(\textit{next}\) array. The length of the array is \(\textit{level}\), indicating the next node at each level. We use a \(\textit{Skiplist}\) class to implement the skip list operations.
The skip list contains a head node \(\textit{head}\) and the current maximum level \(\textit{level}\). The head node's value is set to \(-1\) to mark the starting position of the list. We use a dynamic array \(\textit{next}\) to store pointers to successor nodes.
For the \(\textit{search}\) operation, we start from the highest level of the skip list and traverse downwards until we find the target node or determine that the target node does not exist. At each level, we use the \(\textit{find\_closest}\) method to jump to the node closest to the target.
For the \(\textit{add}\) operation, we first randomly decide the level of the new node. Then, starting from the highest level, we find the node closest to the new value at each level and insert the new node at the appropriate position. If the level of the inserted node is greater than the current maximum level of the skip list, we need to update the level of the skip list.
For the \(\textit{erase}\) operation, similar to the search operation, we traverse each level of the skip list to find and delete the target node. When deleting a node, we need to update the \(\textit{next}\) pointers at each level. If the highest level of the skip list has no nodes, we need to decrease the level of the skip list.
Additionally, we define a \(\textit{random\_level}\) method to randomly decide the level of the new node. This method generates a random number between \([1, \textit{max\_level}]\) until the generated random number is greater than or equal to \(\textit{p}\). We also have a \(\textit{find\_closest}\) method to find the node closest to the target value at each level.
The time complexity of the above operations is \(O(\log n)\), where \(n\) is the number of nodes in the skip list. The space complexity is \(O(n)\).
classNode:__slots__=['val','next']def__init__(self,val:int,level:int):self.val=valself.next=[None]*levelclassSkiplist:max_level=32p=0.25def__init__(self):self.head=Node(-1,self.max_level)self.level=0defsearch(self,target:int)->bool:curr=self.headforiinrange(self.level-1,-1,-1):curr=self.find_closest(curr,i,target)ifcurr.next[i]andcurr.next[i].val==target:returnTruereturnFalsedefadd(self,num:int)->None:curr=self.headlevel=self.random_level()node=Node(num,level)self.level=max(self.level,level)foriinrange(self.level-1,-1,-1):curr=self.find_closest(curr,i,num)ifi<level:node.next[i]=curr.next[i]curr.next[i]=nodedeferase(self,num:int)->bool:curr=self.headok=Falseforiinrange(self.level-1,-1,-1):curr=self.find_closest(curr,i,num)ifcurr.next[i]andcurr.next[i].val==num:curr.next[i]=curr.next[i].next[i]ok=Truewhileself.level>1andself.head.next[self.level-1]isNone:self.level-=1returnokdeffind_closest(self,curr:Node,level:int,target:int)->Node:whilecurr.next[level]andcurr.next[level].val<target:curr=curr.next[level]returncurrdefrandom_level(self)->int:level=1whilelevel<self.max_levelandrandom.random()<self.p:level+=1returnlevel# Your Skiplist object will be instantiated and called as such:# obj = Skiplist()# param_1 = obj.search(target)# obj.add(num)# param_3 = obj.erase(num)
classSkiplist{privatestaticfinalintMAX_LEVEL=32;privatestaticfinaldoubleP=0.25;privatestaticfinalRandomRANDOM=newRandom();privatefinalNodehead=newNode(-1,MAX_LEVEL);privateintlevel=0;publicSkiplist(){}publicbooleansearch(inttarget){Nodecurr=head;for(inti=level-1;i>=0;--i){curr=findClosest(curr,i,target);if(curr.next[i]!=null&&curr.next[i].val==target){returntrue;}}returnfalse;}publicvoidadd(intnum){Nodecurr=head;intlv=randomLevel();Nodenode=newNode(num,lv);level=Math.max(level,lv);for(inti=level-1;i>=0;--i){curr=findClosest(curr,i,num);if(i<lv){node.next[i]=curr.next[i];curr.next[i]=node;}}}publicbooleanerase(intnum){Nodecurr=head;booleanok=false;for(inti=level-1;i>=0;--i){curr=findClosest(curr,i,num);if(curr.next[i]!=null&&curr.next[i].val==num){curr.next[i]=curr.next[i].next[i];ok=true;}}while(level>1&&head.next[level-1]==null){--level;}returnok;}privateNodefindClosest(Nodecurr,intlevel,inttarget){while(curr.next[level]!=null&&curr.next[level].val<target){curr=curr.next[level];}returncurr;}privatestaticintrandomLevel(){intlevel=1;while(level<MAX_LEVEL&&RANDOM.nextDouble()<P){++level;}returnlevel;}staticclassNode{intval;Node[]next;Node(intval,intlevel){this.val=val;next=newNode[level];}}}/** * Your Skiplist object will be instantiated and called as such: * Skiplist obj = new Skiplist(); * boolean param_1 = obj.search(target); * obj.add(num); * boolean param_3 = obj.erase(num); */
structNode{intval;vector<Node*>next;Node(intv,intlevel):val(v),next(level,nullptr){}};classSkiplist{public:constintp=RAND_MAX/4;constintmaxLevel=32;Node*head;intlevel;Skiplist(){head=newNode(-1,maxLevel);level=0;}boolsearch(inttarget){Node*curr=head;for(inti=level-1;~i;--i){curr=findClosest(curr,i,target);if(curr->next[i]&&curr->next[i]->val==target)returntrue;}returnfalse;}voidadd(intnum){Node*curr=head;intlv=randomLevel();Node*node=newNode(num,lv);level=max(level,lv);for(inti=level-1;~i;--i){curr=findClosest(curr,i,num);if(i<lv){node->next[i]=curr->next[i];curr->next[i]=node;}}}boolerase(intnum){Node*curr=head;boolok=false;for(inti=level-1;~i;--i){curr=findClosest(curr,i,num);if(curr->next[i]&&curr->next[i]->val==num){curr->next[i]=curr->next[i]->next[i];ok=true;}}while(level>1&&!head->next[level-1])--level;returnok;}Node*findClosest(Node*curr,intlevel,inttarget){while(curr->next[level]&&curr->next[level]->val<target)curr=curr->next[level];returncurr;}intrandomLevel(){intlv=1;while(lv<maxLevel&&rand()<p)++lv;returnlv;}};/** * Your Skiplist object will be instantiated and called as such: * Skiplist* obj = new Skiplist(); * bool param_1 = obj->search(target); * obj->add(num); * bool param_3 = obj->erase(num); */
funcinit(){rand.Seed(time.Now().UnixNano())}const(maxLevel=16p=0.5)typenodestruct{valintnext[]*node}funcnewNode(val,levelint)*node{return&node{val:val,next:make([]*node,level),}}typeSkipliststruct{head*nodelevelint}funcConstructor()Skiplist{returnSkiplist{head:newNode(-1,maxLevel),level:1,}}func(this*Skiplist)Search(targetint)bool{p:=this.headfori:=this.level-1;i>=0;i--{p=findClosest(p,i,target)ifp.next[i]!=nil&&p.next[i].val==target{returntrue}}returnfalse}func(this*Skiplist)Add(numint){level:=randomLevel()iflevel>this.level{this.level=level}node:=newNode(num,level)p:=this.headfori:=this.level-1;i>=0;i--{p=findClosest(p,i,num)ifi<level{node.next[i]=p.next[i]p.next[i]=node}}}func(this*Skiplist)Erase(numint)bool{ok:=falsep:=this.headfori:=this.level-1;i>=0;i--{p=findClosest(p,i,num)ifp.next[i]!=nil&&p.next[i].val==num{p.next[i]=p.next[i].next[i]ok=true}}forthis.level>1&&this.head.next[this.level-1]==nil{this.level--}returnok}funcfindClosest(p*node,level,targetint)*node{forp.next[level]!=nil&&p.next[level].val<target{p=p.next[level]}returnp}funcrandomLevel()int{level:=1forlevel<maxLevel&&rand.Float64()<p{level++}returnlevel}/** * Your Skiplist object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Search(target); * obj.Add(num); * param_3 := obj.Erase(num); */
classNode{val:number;next:(Node|null)[];constructor(val:number,level:number){this.val=val;this.next=Array(level).fill(null);}}classSkiplist{privatestaticmaxLevel:number=32;privatestaticp:number=0.25;privatehead:Node;privatelevel:number;constructor(){this.head=newNode(-1,Skiplist.maxLevel);this.level=0;}search(target:number):boolean{letcurr=this.head;for(leti=this.level-1;i>=0;i--){curr=this.findClosest(curr,i,target);if(curr.next[i]&&curr.next[i]!.val===target){returntrue;}}returnfalse;}add(num:number):void{letcurr=this.head;constlevel=this.randomLevel();constnode=newNode(num,level);this.level=Math.max(this.level,level);for(leti=this.level-1;i>=0;i--){curr=this.findClosest(curr,i,num);if(i<level){node.next[i]=curr.next[i];curr.next[i]=node;}}}erase(num:number):boolean{letcurr=this.head;letok=false;for(leti=this.level-1;i>=0;i--){curr=this.findClosest(curr,i,num);if(curr.next[i]&&curr.next[i]!.val===num){curr.next[i]=curr.next[i]!.next[i];ok=true;}}while(this.level>1&&this.head.next[this.level-1]===null){this.level--;}returnok;}privatefindClosest(curr:Node,level:number,target:number):Node{while(curr.next[level]&&curr.next[level]!.val<target){curr=curr.next[level]!;}returncurr;}privaterandomLevel():number{letlevel=1;while(level<Skiplist.maxLevel&&Math.random()<Skiplist.p){level++;}returnlevel;}}/** * Your Skiplist object will be instantiated and called as such: * var obj = new Skiplist() * var param_1 = obj.search(target) * obj.add(num) * var param_3 = obj.erase(num) */