#2487

Remove Nodes From Linked List

Medium
Linked ListStackRecursionMonotonic StackMonotonic StackTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach uses a stack to keep track of nodes that should remain in the list. By processing the list from the end to the beginning, we can efficiently determine which nodes to keep based on the maximum value seen so far.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty stack and a variable to track the maximum value seen so far.
  2. 2Step 2: Traverse the linked list from the end to the start.
  3. 3Step 3: For each node, if its value is greater than the maximum value seen, push it onto the stack and update the maximum value.
  4. 4Step 4: After processing all nodes, pop from the stack to reconstruct the linked list in the correct order.
solution.py22 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 removeNodes(head):
8    stack = []
9    max_val = float('-inf')
10    current = head
11    while current:
12        if current.val > max_val:
13            stack.append(current)
14            max_val = current.val
15        current = current.next
16    dummy = ListNode(0)
17    tail = dummy
18    while stack:
19        tail.next = stack.pop()
20        tail = tail.next
21    tail.next = None
22    return dummy.next

Complexity note: The time complexity is O(n) because we traverse the linked list once. The space complexity is O(n) due to the stack storing nodes.

  • 1Iterating from the end allows us to keep track of the maximum value efficiently.
  • 2Using a stack helps in maintaining the order of nodes that need to be kept.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.