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
๐Ÿ”๏ธ Mountain Peak Visibility Analogy521338Horizon Line (Right Direction)ObserverVisible Peak (Kept)Hidden Peak (Removed)Only peaks 13 and 8 are visible from the right - they survive!
Understanding the Visualization
1
Survey from Right
Start from the rightmost peak (node 8) - it's always visible since nothing blocks it
2
Check Peak 3
Peak 3 is blocked by peak 8 (8 > 3), so it becomes invisible
3
Discover Peak 13
Peak 13 is taller than peak 8, so it becomes visible and peak 8 remains visible behind it
4
Filter Remaining
Peaks 2 and 5 are both blocked by the tall peak 13, so they become invisible
Key Takeaway
๐ŸŽฏ Key Insight: Process from right to left using a monotonic decreasing stack. A node survives if there's no strictly greater value to its right, which we can determine efficiently by maintaining the maximum values seen so far.
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