Linked List
A linear collection of data elements whose order is not given by their physical placement in memory. Memory storage does not have to be contiguous as each element contains an address to the next element.
Time Complexityβ
| Operation | Big-O | Note |
|---|---|---|
| Access | O(n) | Must traverse from start |
| Search | O(n) | |
| Insert | O(1) | Assuming you are at the node of insertion |
| Remove | O(1) | Assuming you are at the node of deletion |
Common Approaches to Linked List Questionsβ
| Pattern | Use when | Example |
|---|---|---|
| Dummy head | The head itself might change: merging, removing, inserting at the front | Merge Two Sorted Lists |
| Fast and slow pointers | Find the middle, detect a cycle, find where the cycle starts | Linked List Cycle |
| Two pointers with a gap | Something "n from the end", in one pass | Remove Nth Node From End of List |
| In-place reversal | Reverse all or part of a list in O(1) space | Reverse Linked list |
| Split, reverse, merge | Palindrome check, reorder list: middle β reverse second half β walk both | Reorder List |
| Hashmap of nodes | O(1) lookup into the list, or cloning with extra pointers | LRU Cache, Copy List with Random Pointer |
Fast and Slow Pointersβ
slow moves one step, fast moves two. When fast hits the end, slow is in the middle. If there is a cycle, fast laps slow and they meet inside it.
def middleNode(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow # second middle for even length
To find where a cycle starts (Linked List Cycle II): after they meet, reset one pointer to head and step both by one. They meet again at the cycle's entry.
In-place Reversalβ
Three pointers: save curr.next, point curr back at prev, advance both.
Figure LL-1: Halfway through reversing 1 β 2 β 3 β 4. Amber nodes already point backwards (red links); the β is the link being cut next. Losing curr.next before you save it drops the rest of the list.
To reverse only part of a list (Reverse Linked List II), stop at the node before the range, reverse right β left + 1 nodes, then reconnect both ends. A dummy head handles left == 1.
Corner casesβ
| Case | What breaks |
|---|---|
| Empty list | head.next raises on None |
| Single node | Middle, reversal and "remove nth" must all still return a valid list |
| Removing the head | Return value must change. Use a dummy head |
| Even vs odd length | Which "middle" you get from fast/slow |
| Cycle | Any while node: loop runs forever |
Example Solutionsβ
Reverse Linked listβ
Solution 1: Recursive Approachβ
# linkedList = [1, 2, 3, 4, 5]
def reverseList(self, head):
# Base case: if 0 or 1 element return that element
if not head or not head.next:
return head
last = self.reverseList(head.next) # [5, 4, 3, 2]
head.next.next = head # [2] -> [1]
head.next = None # [1] -> None
return last # [5, 4, 3, 2, 1]
Time Complexity: O(n) for looping through the linked list.
Space Complexity: O(n) for recursive stack of size n.
Solution 2: Iterative Approach (Prefered Solution)β
def reverseList(self, head):
prev = None
while head:
curr = head # curr = [1]
head = head.next # head = [2]
curr.next = prev # [1](curr) -> None(prev)
prev = curr # prev = [1]
return prev
Time Complexity: O(n) for looping through the linked list.
Space Complexity: O(1) for constant variables.
Linked List Cycleβ
Solution: Two Pointersβ
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def hasCycle(self, head):
fast = slow = head
while fast and fast.next: # only need to check fast pointer as it is in front of slow pointer
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
Time Complexity: O(n). See here
- Case 1: No cycle
- Fast pointer reaches the end in
n/2steps => O(n)
- Fast pointer reaches the end in
- Case 2: Cycle exists
- Once the slower node reaches the cycle, the faster node catches up to the slower node in
ksteps, wherekis the length of cycle. O((n - k) + k) => O(n)
- Once the slower node reaches the cycle, the faster node catches up to the slower node in
Space Complexity: O(1) for 2 constant variables fast and slow.
Merge Two Sorted Listsβ
Solution: Dummy Headβ
A dummy node removes the "which list supplies the head?" special case. Splice the smaller node onto tail until one list runs out, then attach the rest of the other in one step.
def mergeTwoLists(self, list1, list2):
dummy = tail = ListNode(0)
while list1 and list2:
if list1.val <= list2.val: # <= keeps equal values in their original order
tail.next, list1 = list1, list1.next
else:
tail.next, list2 = list2, list2.next
tail = tail.next
tail.next = list1 or list2 # at most one is non-empty
return dummy.next
Time Complexity: O(n + m), each node is visited once.
Space Complexity: O(1), nodes are relinked, not copied.
Remove Nth Node From End of Listβ
Excellent leetcode explanation by sgallivan.
Solution: Two Pointersβ
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def removeNthFromEnd(self, head, n):
fast = slow = head
# Move fast pointer first
for _ in range(n):
fast = fast.next
# Edge case: n == len(list), remove first node
if not fast:
return head.next
# Move both pointer until fast reaches the end
while fast.next:
slow = slow.next
fast = fast.next
# Remove nth node
slow.next = slow.next.next
return head
Edge case explanation: when n == len(list), we want to remove the first node. fast would reach the end of the list and be equal to None, hence we check that fast == None.
Time Complexity: O(n) as it is a one pass algorithm.
Space Complexity: O(1) for 2 constant variables fast and slow.