MediumNo. 2487
Remove Nodes From Linked List — LeetCode 2487 Python Solution
- Pattern
- Linked List
- Topics
- Stack, Recursion, Linked List, Monotonic Stack
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given the head of a linked list. Remove every node which has a node with a greater value anywhere to the right side of it.
Example
- Input
- head = [5,2,13,3,8]
- Output
- [13,8]
- Explanation
- The nodes that should be removed are 5, 2 and 3.
Python solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
nums = []
while head:
nums.append(head.val)
head = head.next
stk = []
for v in nums:
while stk and stk[-1] < v:
stk.pop()
stk.append(v)
dummy = ListNode()
head = dummy
for v in stk:
head.next = ListNode(v)
head = head.next
return dummy.nextComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)where n is the length of the linked list
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2487. Remove Nodes From Linked List is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1019 | Next Greater Node In Linked List | Medium |
| 2289 | Steps to Make Array Non-decreasing | Medium |
| 0084 | Largest Rectangle in Histogram | Hard |
| 0456 | 132 Pattern | Medium |
| 0503 | Next Greater Element II | Medium |
| 0654 | Maximum Binary Tree | Medium |
Frequently asked questions
- How hard is LeetCode 2487. Remove Nodes From Linked List?
LeetCode 2487. Remove Nodes From Linked List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2487. Remove Nodes From Linked List?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2487. Remove Nodes From Linked List?
The Python solution on this page uses O(n), where n is the length of the linked list auxiliary space.
- What topics does LeetCode 2487. Remove Nodes From Linked List cover?
LeetCode 2487. Remove Nodes From Linked List is tagged Stack, Recursion, Linked List and Monotonic Stack on LeetCode.