The problem
Build a class Line: a line of values that can grow and shrink at both ends. Every method except to_list must take O(1) time, however long the line is.
L = Line()
L.add_last(1); L.add_last(2); L.add_first(0)
L.to_list() # [0, 1, 2]
L.remove_first() # 0
L.remove_last() # 2
len(L) # 1
L.remove_last() # 1
L.remove_last() # None: the line is empty
collections.deque does exactly this, so it is switched off. Build it yourself from nodes. A Python list will not do either: insert(0, x) and pop(0) move every item, so they are O(n).
Limits
- Up to 200,000 operations in one test.
- The tests call the methods and compare what each one returns.
Builds on LINK-3 Doubly and circular 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.
8 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Add at both ends | Not run | |
| 2 | Remove from both ends | Not run | |
| 3 | Empty line | Not run | |
| 4 | Down to empty and back | Not run | |
| 5 | Length | Not run | |
| 6 | Mixed | Not run | |
| 7 | 200,000 at the front | Not run | |
| 8 | Both ends, 200,000 adds | Not run |