The problem
Build a skip list (lesson 6) of different keys, with these methods:
add(key): put the key in. If it is already there, do nothing.contains(key):Trueif the key is there.remove(key): take the key out and returnTrue; returnFalseif it was not there.first_at_least(key): the smallest key that is at leastkey, orNoneif there is none.
s = SkipList()
s.add(10); s.add(20); s.add(30)
s.first_at_least(15) # 20
s.first_at_least(31) # None
s.remove(20) # True
Keep the shape from the starter code: self.head is a node whose list next has one link per level, and each key’s node has a list next as long as its tower. One test walks your levels through head.next[0], head.next[1] and head.next[2]: level 0 must hold every key in order. Give each new key a tower: start at level 0, then flip a fair coin (random.random() < 0.5 means heads). Each heads adds one level, and the first tails stops. So about half the keys reach level 1, and about a quarter reach level 2. The bisect module is switched off.
Limits
- Up to 30,000 keys and about 50,000 operations; each should take O(log n) time on average.
Builds on BALT-6 Skip lists.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Add and find | Not run | |
| 2 | Empty list | Not run | |
| 3 | Remove | Not run | |
| 4 | First key at least x | Not run | |
| 5 | Repeats | Not run | |
| 6 | Negative keys | Not run | |
| 7 | The shape | Not run | |
| 8 | Big | Not run |