↓Skip to main content
  1. LeetCode/

LeetCode 2487: Remove Nodes From Linked List

·1 min· ·
LeetCode Medium Linked-List Stack Recursion Monotonic-Stack
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2024-05-06

  • Submissions: Accepted ×3

Approach
#

A node stays when nothing to its right is larger. Scan left to right with a stack (Stack, monotonic stack): when a node arrives, every smaller node on top now has something larger to its right, so pop them. The stack ends non-increasing bottom to top; link it in order (Linked List Template 2 mentions the alternative of reversing first).

My Solution
#

class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        stack = []
        while head:
            while stack and stack[-1].val < head.val:
                stack.pop()
            stack.append(head)
            head = head.next
        for a, b in zip(stack, stack[1:]):
            a.next = b
        stack[-1].next = None
        return stack[0]

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Pop only strictly smaller nodes; equal ones stay.
  • Set the last node’s next to None.

Interview Explanation
#

Kept nodes have nothing larger to their right, so I keep a monotonic stack that pops smaller nodes when a new one arrives, then link the remaining nodes in order. Time O(n).

Related

LeetCode 143: Reorder List
·2 mins
LeetCode Medium Linked-List Two-Pointers Stack Recursion
LeetCode 143 note: find the middle, reverse the second half, and merge the two alternately, cutting the first half’s tail
LeetCode 402: Remove K Digits
·2 mins
LeetCode Medium String Stack Greedy Monotonic-Stack
LeetCode 402 note: a monotonically increasing stack; while deletions remain, pop any top larger than the current digit, then strip leading zeros
LeetCode 24: Swap Nodes in Pairs
·2 mins
LeetCode Medium Linked-List Recursion
LeetCode 24 note: a dummy plus pairs, rewiring prev.next, a.next and b.next together; swap nodes, not values
LeetCode 234: Palindrome Linked List
·2 mins
LeetCode Easy Linked-List Two-Pointers Stack Recursion
LeetCode 234 note: find the middle with fast and slow pointers, reverse the second half, and compare from both ends with O(1) extra space
LeetCode 2: Add Two Numbers
·2 mins
LeetCode Medium Linked-List Math Recursion
LeetCode 2 note: digits are stored in reverse, so add from the head digit by digit with a carry, looping until both lists end and no carry remains
LeetCode 735: Asteroid Collision
·2 mins
LeetCode Medium Array Stack Simulation
LeetCode 735 note: scan left to right with a stack; only a right-moving top meeting a left-moving asteroid collides, the smaller explodes and equal sizes both do