Skip to main content

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​

OperationBig-ONote
AccessO(n)Must traverse from start
SearchO(n)
InsertO(1)Assuming you are at the node of insertion
RemoveO(1)Assuming you are at the node of deletion

Common Approaches to Linked List Questions​

PatternUse whenExample
Dummy headThe head itself might change: merging, removing, inserting at the frontMerge Two Sorted Lists
Fast and slow pointersFind the middle, detect a cycle, find where the cycle startsLinked List Cycle
Two pointers with a gapSomething "n from the end", in one passRemove Nth Node From End of List
In-place reversalReverse all or part of a list in O(1) spaceReverse Linked list
Split, reverse, mergePalindrome check, reorder list: middle β†’ reverse second half β†’ walk bothReorder List
Hashmap of nodesO(1) lookup into the list, or cloning with extra pointersLRU 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.

None1234Noneprevcurrβœ•

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​

CaseWhat breaks
Empty listhead.next raises on None
Single nodeMiddle, reversal and "remove nth" must all still return a valid list
Removing the headReturn value must change. Use a dummy head
Even vs odd lengthWhich "middle" you get from fast/slow
CycleAny 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/2 steps => O(n)
  • Case 2: Cycle exists
    • Once the slower node reaches the cycle, the faster node catches up to the slower node in k steps, where k is the length of cycle. O((n - k) + k) => O(n)

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​

tip

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.