Remove Nodes From Linked List - Problem

You are given the head of a linked list. Your task is to remove every node that has a node with a strictly greater value anywhere to the right side of it.

Think of it this way: a node survives if it's the maximum among all nodes from its position to the end of the list. All other nodes should be eliminated!

Example: In the list [5,2,13,3,8], node 5 gets removed because 13 > 5, node 2 gets removed because 13 > 2, node 3 gets removed because 8 > 3. The result is [13,8].

Return the head of the modified linked list.

Input & Output

example_1.py — Standard Case
$ Input: head = [5,2,13,3,8]
Output: [13,8]
💡 Note: Node 5 is removed because 13 > 5. Node 2 is removed because 13 > 2. Node 3 is removed because 8 > 3. Nodes 13 and 8 have no greater values to their right, so they remain.
example_2.py — Ascending Order
$ Input: head = [1,1,1,1]
Output: [1,1,1,1]
💡 Note: No node has a strictly greater value to its right (all values are equal), so all nodes remain in the list.
example_3.py — Single Node
$ Input: head = [1]
Output: [1]
💡 Note: A single node has no nodes to its right, so it always remains in the list.

Constraints

  • The number of nodes in the list is in the range [1, 105]
  • 1 ≤ Node.val ≤ 105
  • Follow-up: Can you solve this in O(n) time and O(1) extra space?

Visualization

Tap to expand
Remove Nodes From Linked List INPUT Original Linked List: 5 2 13 3 8 NULL Nodes to Remove: 5 2 3 (have larger to right) head = [5, 2, 13, 3, 8] 5 nodes in original list ALGORITHM STEPS 1 Reverse List Process from end: 8,3,13,2,5 2 Track Maximum Keep max seen so far 3 Keep Only Max Nodes Node stays if val >= max 4 Reverse Back Get final order: 13,8 Traversal (reversed): Node Max Action 8 8 KEEP (new max) 3 8 REMOVE (3<8) 13 13 KEEP (new max) 2 13 REMOVE (2<13) 5 13 REMOVE (5<13) FINAL RESULT Modified Linked List: 13 8 NULL Only 2 nodes remain! Why these survive: 13: No larger value to right 8: No larger value to right (8 is at the end) Output: [13, 8] OK - Verified Key Insight: A node survives ONLY if it's the maximum from its position to the end. By reversing the list, we can track the running maximum and keep nodes that set new maximums. Time: O(n), Space: O(1). Alternative: Use a monotonic stack to process right-to-left without explicit reversal. TutorialsPoint - Remove Nodes From Linked List | Optimal Solution (Reverse + Track Max)
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen