Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Sequences and memory
EXPERIMENT 07 / 66

A way back as well as forward.

Maintain next and previous links without losing the surrounding chain.

BY NAVAN SAMI◷ 8 MIN READSTARTERSTRUCTURE

01 Model the idea

A doubly linked node has references in both directions. This makes backward traversal and removal of a known interior node convenient, but it costs additional storage and creates more link invariants to maintain. Finding a node by value is still a traversal. Efficient local edits do not imply constant-time search.

THE THING THAT MUST STAY TRUE

Adjacent next/prev references are reciprocal.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
RECONNECT the previous node to the next
RECONNECT the next node to the previous
UPDATE head or tail if a boundary changed

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

doubly_linked_lists.py
class Node:
    def __init__(self, value): self.value, self.prev, self.next = value, None, None
first, middle, last = Node("A"), Node("B"), Node("C")
first.next, middle.prev = middle, first
middle.next, last.prev = last, middle
middle.prev.next = middle.next
middle.next.prev = middle.prev
print(first.next.value)
print(last.prev.value)
↳ EXPECTED OUTPUT
C
A
  1. 1

    The fixture creates reciprocal links: if x.next is y, y.prev should be x. Removing the middle node reconnects its two neighbours.

  2. 2

    Removing a head or tail requires updating the owning list’s endpoint references. Sentinel nodes can make those boundary cases more uniform.

  3. 3

    A known-node removal is constant-time pointer work. Searching for the node remains linear, and memory locality can be worse than a contiguous array representation.

04 Count the cost

TIME

O(1) unlink after locating an interior node; O(n) search

SPACE

O(n) node storage

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Build two reciprocal nodes and verify the forward/backward invariant.

Reveal one possible solution +
one_possible_solution.py
class Node:
    def __init__(self, value): self.value, self.prev, self.next = value, None, None
a, b = Node(1), Node(2)
a.next, b.prev = b, a
assert a.next.prev is a and b.prev.next is b
print("Reciprocal links verified")

06 Check your reasoning

QUICK SIGNAL CHECK

What extra invariant comes with doubly linked nodes?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.