Skip List Implementation - Problem
A skip list is a probabilistic data structure that allows O(log n) search complexity in a sorted sequence of elements. It maintains multiple levels of linked lists, where each higher level acts as an "express lane" for the levels below it.
Implement a skip list with the following operations:
- SkipList() - Initialize the skip list
- search(target) - Return
trueiftargetexists in the skip list,falseotherwise - add(num) - Insert
numinto the skip list - erase(num) - Remove one occurrence of
numfrom the skip list. Returntrueif successfully removed,falseif not found
The skip list should handle duplicate values and maintain sorted order. For simplicity, use a fixed probability of 0.5 for promoting elements to higher levels, and limit the maximum number of levels to 16.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["SkipList","add","add","search","erase","add","add","search"]
values = [0,1,2,1,1,2,3,2]
›
Output:
[null,null,null,true,true,null,null,true]
💡 Note:
Initialize skip list, add 1 and 2, search for 1 (found), erase 1 (success), add 2 and 3, search for 2 (found)
Example 2 — Search Non-existent
$
Input:
operations = ["SkipList","add","search","search"]
values = [0,5,5,10]
›
Output:
[null,null,true,false]
💡 Note:
Add 5, search for 5 (found), search for 10 (not found)
Example 3 — Duplicate Values
$
Input:
operations = ["SkipList","add","add","erase","search"]
values = [0,3,3,3,3]
›
Output:
[null,null,null,true,true]
💡 Note:
Add 3 twice, erase one occurrence of 3 (success), one 3 still remains
Constraints
- 0 ≤ num, target ≤ 2 × 104
- At most 5 × 104 calls will be made to search, add, and erase
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code