LINK-P2

A two-way line

Practice 2 of 6Linked lists8 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Add at both endsNot run
2Remove from both endsNot run
3Empty lineNot run
4Down to empty and backNot run
5LengthNot run
6MixedNot run
7200,000 at the frontNot run
8Both ends, 200,000 addsNot run