Design Linked List solution explained
To design a linked list class, keep a sentinel node in front of index 0 and a size counter: every operation then walks to the node just before the target index and re-links one or two pointers, with no special case for the head. Check the index against size first so invalid calls do nothing. In this Design Linked List solution, get, add and delete at an index cost O(index) in a singly linked list, and a doubly linked version with two sentinels walks from the nearer end, at most n/2 steps.
By Evin JohnPublished 7 min read
The task, restated
Build a linked list from scratch, without using the language's built-in list as storage. It holds integers, indexed from 0, and supports: reading the value at an index, adding at the front, adding at the back, inserting before a given index, and deleting at an index. You choose singly or doubly linked.
| Operation | Valid indexes (size n) | When the index is invalid |
|---|---|---|
| get(i) | 0 to n - 1 | Return -1 |
| addAtIndex(i, v) | 0 to n; i = n appends | Do nothing |
| deleteAtIndex(i) | 0 to n - 1 | Do nothing |
| addAtHead(v), addAtTail(v) | Always valid | Not applicable |
Agree on these rules before writing code, because versions of this exercise differ. Some treat a negative insert index as "insert at the head"; some raise an error instead of returning -1. Whatever the interviewer picks, write it down and check it at the top of each method, so the rest of the code can assume a valid index.
| Call | List afterwards | Returns |
|---|---|---|
| addAtTail(5) | 5 | |
| addAtHead(2) | 2 → 5 | |
| addAtIndex(1, 9) | 2 → 9 → 5 | |
| addAtIndex(3, 4) | 2 → 9 → 5 → 4 | i = n, so it appends |
| addAtIndex(6, 1) | 2 → 9 → 5 → 4 | i > n, ignored |
| get(2) | unchanged | 5 |
| deleteAtIndex(0) | 9 → 5 → 4 | |
| get(3) | unchanged | -1 |
How interviewers use it
This is a design exercise more than an algorithm. The interviewer watches how you handle boundaries: empty lists, index 0, the last index, and index equal to the size. Candidates who reach for a sentinel early tend to write half as many branches. It also opens the door to trade-off questions: why keep a size field, why keep a tail pointer, when to go doubly linked.
- Make addAtTail O(1). Keep a tail pointer, and update it whenever the last node is inserted after or deleted.
- Support reverse traversal. Add prev pointers and a tail sentinel; the JavaScript version below does this.
- Make it generic or iterable. Add a type parameter or an iterator that walks from the sentinel.
- Implement an LRU cache on top. A doubly linked list plus a hash map gives O(1) moves to the front.
Singly linked with one sentinel
The sentinel is a dummy node that always sits before index 0. A helper returns the node just before position i by walking i steps from the sentinel. Inserting at i links a new node after that predecessor; deleting at i skips over the predecessor's next. Because the sentinel exists even in an empty list, index 0 needs no special handling.
class Node:
__slots__ = ("val", "next")
def __init__(self, val, nxt=None):
self.val = val
self.next = nxt
class MyLinkedList:
def __init__(self):
self.sentinel = Node(0) # always sits before index 0
self.size = 0
def _before(self, index):
node = self.sentinel
for _ in range(index):
node = node.next
return node
def get(self, index):
if index < 0 or index >= self.size:
return -1
return self._before(index).next.val
def add_at_index(self, index, val):
if index < 0 or index > self.size:
return
prev = self._before(index)
prev.next = Node(val, prev.next)
self.size += 1
def add_at_head(self, val):
self.add_at_index(0, val)
def add_at_tail(self, val):
self.add_at_index(self.size, val)
def delete_at_index(self, index):
if index < 0 or index >= self.size:
return
prev = self._before(index)
prev.next = prev.next.next
self.size -= 1add_at_head and add_at_tail delegate to add_at_index, so there is only one insertion path to get right. The cost is that add_at_tail walks the whole list; the first follow-up above fixes that.
Doubly linked with two sentinels
With a sentinel at each end, every real node has a real node on both sides, so insertion and deletion never check for null. Keeping the size also tells you which end is closer: indexes in the first half are reached from the head, the rest from the tail.
class MyLinkedList {
constructor() {
this.head = { val: 0, prev: null, next: null };
this.tail = { val: 0, prev: null, next: null };
this.head.next = this.tail;
this.tail.prev = this.head;
this.size = 0;
}
// The node at position index, for 0 <= index < size.
nodeAt(index) {
if (index < this.size / 2) {
let node = this.head.next;
for (let i = 0; i < index; i++) node = node.next;
return node;
}
let node = this.tail.prev;
for (let i = this.size - 1; i > index; i--) node = node.prev;
return node;
}
get(index) {
if (index < 0 || index >= this.size) return -1;
return this.nodeAt(index).val;
}
addAtIndex(index, val) {
if (index < 0 || index > this.size) return;
const after = index === this.size ? this.tail : this.nodeAt(index);
const before = after.prev;
const node = { val, prev: before, next: after };
before.next = node;
after.prev = node;
this.size++;
}
addAtHead(val) { this.addAtIndex(0, val); }
addAtTail(val) { this.addAtIndex(this.size, val); }
deleteAtIndex(index) {
if (index < 0 || index >= this.size) return;
const node = this.nodeAt(index);
node.prev.next = node.next;
node.next.prev = node.prev;
this.size--;
}
}Here addAtTail is O(1), because the walk for index = size is skipped in favor of the tail sentinel directly. The price is an extra pointer per node and two pointer updates per change instead of one.
Time and space
| Operation | Singly linked, one sentinel | Doubly linked, two sentinels |
|---|---|---|
| get(i) | O(i) | O(min(i, n - i)) |
| addAtHead | O(1) | O(1) |
| addAtTail | O(n), or O(1) with a tail pointer | O(1) |
| addAtIndex(i) | O(i) | O(min(i, n - i)) |
| deleteAtIndex(i) | O(i) | O(min(i, n - i)) |
| Memory | One pointer per node | Two pointers per node |
Edge cases
- Operations on an empty list: get(0) returns -1, deleteAtIndex(0) does nothing, addAtIndex(0, v) works.
- addAtIndex with index equal to the size appends; one past that is ignored.
- Deleting the only node, then adding again.
- Negative indexes, which this spec rejects; confirm the interviewer's rule.
- Deleting the last node when a tail pointer is kept: the tail must move back.
Mistakes to avoid
- Writing separate head, middle and tail branches instead of using a sentinel.
- Forgetting to update size on one of the paths, so later bounds checks drift.
- Allowing insert at size + 1 or delete at size because the bounds use the wrong comparison.
- In the doubly linked version, updating next but not prev on one side.
- Keeping a tail pointer and not fixing it when the last node is deleted.
How to explain it out loud
Fictional example
- Candidate
- Before I code, the index rules: get and delete accept 0 to size minus 1, insert accepts 0 to size, and size means append. Anything else is ignored, and get returns -1. Does that match what you want?
- Candidate
- I will keep a sentinel before index 0 and a size field. Then every operation is: validate, walk to the node before the index, re-link.
- Candidate
- That makes head insert O(1) and everything else O(index). If tail inserts are frequent, I would switch to a doubly linked list with a tail sentinel.
Related walkthroughs
LRU Cache is the classic use of a doubly linked list with sentinels, combined with a hash map. Restore IP Addresses is another problem where writing the validity rules down first prevents most bugs. Rotate List practices re-linking at a computed index.
Where Natively fits
When you rehearse class-design questions on a Mac or Windows PC, Natively can read the method list from a screenshot and write an approach and code in the overlay, which helps you check your bounds against another version after you have written your own. A transcript of your mock session shows whether you confirmed the index rules before coding. The AI interview assistant page has the details.
Questions people ask
How do you design a linked list class?
Keep a sentinel node before index 0 and a size counter. Each method checks the index against the size, walks to the node before the target, and re-links one or two pointers.
Why use a sentinel node in a linked list?
It means the list always has a node before the first element, so inserting or deleting at index 0 works like any other index, with no special case.
What is the time complexity of Design Linked List operations?
O(index) for get, insert and delete in a singly linked list, O(1) at the head. A doubly linked list with a tail sentinel makes tail inserts O(1) and walks from the nearer end.
Should Design Linked List be singly or doubly linked?
Singly linked is simpler and uses less memory. Doubly linked costs an extra pointer per node but makes tail operations and reverse walks cheap.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
