Remove Nodes From Linked List (LeetCode 2487): Solution and Explanation
Given the head of a linked list, delete every node that has a strictly greater value somewhere to its right, and return the new head.
Intuition
A node survives only if every value after it is less than or equal to its own. Read left to right, the survivors therefore never increase.
That is the shape a monotonic stack keeps. Walk the list and hold the survivors so far on a stack whose values never increase from bottom to top.
When a new node arrives, every smaller node on top of the stack now has something bigger to its right, so it is popped for good. A node that is not smaller stays, and so does everything under it.
After the pops, the stack top is the survivor just before the new node, so pointing its next at the new node keeps the list correctly linked as it is built.
Approach: Monotonic stack with in-place relinking
- Start with an empty stack and
node = head. - While the stack top's value is less than
node.val, pop it. - If the stack is not empty, set
stack[-1].next = node. - Push
nodeand move tonode.next. - When the list ends, return
stack[0], the bottom of the stack.
Step-by-step example
head = [5,2,13,3,8]
- Push 5. 2 is not bigger than 5, so 5.next stays 2 and 2 is pushed. Stack [5,2].
- 13 is bigger than 2, pop it. 13 is bigger than 5, pop it. Push 13. Stack [13].
- 3 is smaller than 13, so 13.next = 3 and 3 is pushed. Stack [13,3].
- 8 is bigger than 3, pop it. 13 is not smaller than 8, so 13.next = 8 and 8 is pushed. Stack [13,8].
- The list ends. Return the bottom node 13: the answer is [13,8].
Code: Python, Java, C++
1class Solution:
2 def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
3 stack = []
4 node = head
5 while node:
6 while stack and stack[-1].val < node.val:
7 stack.pop()
8 if stack:
9 stack[-1].next = node
10 stack.append(node)
11 node = node.next
12 return stack[0]1class Solution {
2 public ListNode removeNodes(ListNode head) {
3 List<ListNode> stack = new ArrayList<>();
4 ListNode node = head;
5 while (node != null) {
6 while (!stack.isEmpty() && stack.get(stack.size() - 1).val < node.val) {
7 stack.remove(stack.size() - 1);
8 }
9 if (!stack.isEmpty()) {
10 stack.get(stack.size() - 1).next = node;
11 }
12 stack.add(node);
13 node = node.next;
14 }
15 return stack.get(0);
16 }
17}1class Solution {
2public:
3 ListNode* removeNodes(ListNode* head) {
4 vector<ListNode*> stk;
5 ListNode* node = head;
6 while (node) {
7 while (!stk.empty() && stk.back()->val < node->val) {
8 stk.pop_back();
9 }
10 if (!stk.empty()) {
11 stk.back()->next = node;
12 }
13 stk.push_back(node);
14 node = node->next;
15 }
16 return stk[0];
17 }
18};Time and space complexity
O(n)
Each node is pushed once and popped at most once, so the total work across all inner loops is linear.
O(n)
In the worst case (a non-increasing list) every node sits on the stack at the end.
Other approaches
Reverse, filter, reverse (time O(n), space O(1))
Reverse the list, walk it keeping a running maximum and dropping nodes smaller than it, then reverse back. This uses O(1) extra space at the cost of two reversals.
Recursion from the tail (time O(n), space O(n))
Process the rest of the list first; keep the current node only if its value is at least the head of the processed rest. Short to write, but recursion depth reaches n = 10^5, which can overflow the call stack.
Check every node against its suffix (time O(n^2), space O(1))
For each node scan everything after it for a bigger value. Correct but quadratic.
Common mistakes
- Popping on equal values. The rule is strictly greater, so equal values must all stay; pop only while the top is smaller.
- Forgetting to relink. Popped nodes are still reachable through the old
nextpointers unless the new top is pointed at the current node. - Returning
head. When the original head is removed, the answer starts at the bottom of the stack instead. - Using recursion on a list of 10^5 nodes, which overflows the default stack in several languages.
Frequently asked questions
Why does the stack always end with the last node?
Nothing comes after the last node, so nothing can be greater than it. It is pushed last and never popped.
Why is the last survivor's next already null?
The last survivor is the original last node, whose next was null from the start. Every other survivor gets its next set when the following survivor is pushed.
How is this related to Next Greater Element?
Both keep a stack in which values never increase. Here a node popped from the stack is exactly a node that found a greater element to its right, which is the reason it gets removed.