Remove Nodes From Linked List

Medium

Topics
Linked ListStackRecursionMonotonic Stack

Given the head of a linked list, remove every node which has a node with a strictly greater value anywhere to its right. Return the head of the modified list.

Example 1

521338null
has a larger value to its right
A node goes if anything to its right is strictly larger.
Linked list values from head to tail.
Input:  head = [5,2,13,3,8]
Output: [13,8]

Example 2

1111null
Input:  head = [1,1,1,1]
Output: [1,1,1,1]

Constraints

  • 1 <= number of nodes <= 10^5
  • 1 <= Node.val <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

A node survives only if nothing to its right is strictly greater, so the surviving list is non-increasing — it is the sequence of running maxima read from the right. Two standard shapes give that: a monotonic stack over a left-to-right pass, or recursion that processes the suffix first.

The shown solution recurses. Each call relinks itself to the already-filtered suffix, then asks a single local question: is the head of that filtered suffix bigger than this node? If so the node is dominated, and the call returns its successor instead of itself. The filtered suffix starts with its maximum, which is why one comparison is enough.

Approach

  1. Recurse to the end of the list.
  2. Set head.next to the filtered suffix that comes back.
  3. If that suffix is non-empty and its first value exceeds head.val, return head.next and drop head.
  4. Otherwise return head.

Dry Run

input  5 -> 2 -> 13 -> 3 -> 8

unwinding from the right, each node sees its already-filtered suffix

  node 8    suffix []        nothing to beat it        -> 8
  node 3    suffix [8]       8 > 3, drop 3             -> 8
  node 13   suffix [8]       8 < 13, keep 13           -> 13 -> 8
  node 2    suffix [13,8]    13 > 2, drop 2            -> 13 -> 8
  node 5    suffix [13,8]    13 > 5, drop 5            -> 13 -> 8

answer  13 -> 8

  [9,7,5]   -> 9 -> 7 -> 5    already non-increasing, nothing is removed
  [1,2,3,4] -> 4              everything is dominated by the last node

Complexity

  • Time — O(n): one call per node, constant work in each.
  • Space — O(n) for the recursion, which is honest rather than O(1): the recursion depth equals the list length. At the stated bound of 10⁵ nodes that is real — Python's default limit of 1,000 is blown immediately, Node's stack gives out between 5,000 and 10,000 frames, and Java's default holds to roughly 20,000. The Python harness on this page raises the limit; the monotonic-stack version is the same O(n) space without the stack-depth exposure, and an explicit-stack or reverse-twice version is O(1) auxiliary.

Common Pitfalls

  • Using >= instead of >. The rule says strictly greater, so equal neighbours must both survive: on [5,5,5] the >= variant returns [5] where the answer is [5,5,5].
  • Comparing against the maximum of the whole remaining suffix computed separately, which is O(n²) when the suffix maximum is recomputed per node.
  • Scanning left to right and deleting greedily. A node's fate depends on values to its right, so a forward pass has to buffer — that buffer is the monotonic stack.
  • Forgetting to reassign head.next before the comparison. The comparison must be against the filtered suffix, not the original one.
  • Building a new list of surviving values instead of relinking. It passes, but the problem is a pointer exercise and the relink is what is being examined.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def removeNodes(self, head):
        if not head:
            return None
        head.next = self.removeNodes(head.next)
        if head.next and head.next.val > head.val:
            return head.next
        return head
SensAI
Beta
Tap the mic to stop voice mode