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 true if target exists in the skip list, false otherwise
  • add(num) - Insert num into the skip list
  • erase(num) - Remove one occurrence of num from the skip list. Return true if successfully removed, false if 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
INPUT OPERATIONSSKIP LIST STRUCTURERESULTS["SkipList","add","add","search"][0, 1, 2, 1]Operation Flow:1. Initialize empty skip list2. Add value 1 (random level)3. Add value 2 (random level)4. Search for value 11234Multi-level structureProbabilistic promotionExpress lane traversalO(log n) search timeLevel 1: [1] -- [2]Level 0: [1] -- [2]Search path: ↓→Operation Results:[null, null, null, true]✓ SkipList initialized✓ Value 1 added successfully✓ Value 2 added successfully✓ Value 1 found in structureKey Insight:Skip lists use probabilistic multi-level structure to achieve O(log n) performance.Higher levels act as "express lanes" that skip over lower-level nodes during traversal.TutorialsPoint - Skip List Implementation | Multi-Level Structure
Asked in
Google 15 Microsoft 12 Amazon 8 Redis 25
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen