Design Skiplist
01 · Problem
Implement a skiplist without using any built-in ordered containers or libraries. A skiplist stores sorted values in several layers of linked lists, where each higher layer skips over more nodes, so that searching, inserting, and deleting take O(log n) time on average.
Implement the Skiplist class:
Skiplist()creates an empty skiplist.bool search(int target)returnstrueiftargetis present at least once, otherwisefalse.void add(int num)insertsnum. Duplicate values are allowed and each copy is stored separately.bool erase(int num)removes one copy ofnumand returnstrue; ifnumis not present, it does nothing and returnsfalse.
The input lists the method names and their arguments; the output lists the return value of each call, with null for the constructor and for add.
02 · Examples
["Skiplist","add","add","add","search","erase","search","erase","search"], [[],[5],[3],[5],[5],[5],[5],[5],[5]]
[null,null,null,null,true,true,true,true,false]
Two copies of 5 are added. The first erase removes one copy, so 5 is still found; the second erase removes the last copy, so the final search returns false.
["Skiplist","search","add","erase","erase","search"], [[],[7],[7],[8],[7],[7]]
[null,false,null,false,true,false]
7 is not found initially. After adding 7, erasing 8 fails because 8 is absent, erasing 7 succeeds, and 7 can no longer be found.
03 · Constraints
- 010 <= num, target <= 2 * 104
- 02At most 5 * 104 calls will be made to search, add, and erase in total.
- 03Built-in sorted containers (TreeMap, std::set, bisect-based structures, etc.) must not be used.
04 · Optimal complexity
- Time
- O(log n) expected per operation
- Space
- O(n) expected
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.