#203
Remove Linked List Elements
EasyLinked ListRecursionLinked ListTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single pass through the linked list, modifying pointers directly to skip over nodes with the value 'val'. This is efficient because it only requires one traversal of the list.
⚙️
Algorithm
5 steps- 1Step 1: Create a dummy node that points to the head of the list.
- 2Step 2: Use a pointer to traverse the list, checking each node's value.
- 3Step 3: If the current node's value equals 'val', skip it by adjusting the previous node's next pointer.
- 4Step 4: If it doesn't equal 'val', move the previous pointer to the current node.
- 5Step 5: Continue until the end of the list, then return the next node of the dummy node.
solution.py18 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def removeElements(head, val):
8 dummy = ListNode(0)
9 dummy.next = head
10 prev = dummy
11 current = head
12 while current:
13 if current.val == val:
14 prev.next = current.next
15 else:
16 prev = current
17 current = current.next
18 return dummy.nextℹ
Complexity note: The time complexity is O(n) because we only traverse the list once. The space complexity is O(1) since we are using a constant amount of extra space.
- 1Using a dummy node simplifies edge cases like removing the head.
- 2Directly modifying pointers avoids the need for additional data structures.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.