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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code