2487. Remove Nodes From Linked List LeetCode Solution

In this guide, you will get 2487. Remove Nodes From Linked List LeetCode Solution with the best time and space complexity. The solution to Remove Nodes From Linked List problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Remove Nodes From Linked List solution in C++
  4. Remove Nodes From Linked List solution in Java
  5. Remove Nodes From Linked List solution in Python
  6. Additional Resources
2487. Remove Nodes From Linked List LeetCode Solution image

Problem Statement of Remove Nodes From Linked List

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.
Return the head of the modified linked list.

Example 1:

Input: head = [5,2,13,3,8]
Output: [13,8]
Explanation: The nodes that should be removed are 5, 2 and 3.
– Node 13 is to the right of node 5.
– Node 13 is to the right of node 2.
– Node 8 is to the right of node 3.

Example 2:

Input: head = [1,1,1,1]
Output: [1,1,1,1]
Explanation: Every node has value 1, so no nodes are removed.

Constraints:

The number of the nodes in the given list is in the range [1, 105].
1 <= Node.val <= 105

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

2487. Remove Nodes From Linked List LeetCode Solution in C++

class Solution {
 public:
  ListNode* removeNodes(ListNode* head) {
    if (head == nullptr)
      return nullptr;
    head->next = removeNodes(head->next);
    return head->next != nullptr && head->val < head->next->val ? head->next
                                                                : head;
  }
};
/* code provided by PROGIEZ */

2487. Remove Nodes From Linked List LeetCode Solution in Java

class Solution {
  public ListNode removeNodes(ListNode head) {
    if (head == null)
      return null;
    head.next = removeNodes(head.next);
    return head.next != null && head.val < head.next.val ? head.next : head;
  }
}
// code provided by PROGIEZ

2487. Remove Nodes From Linked List LeetCode Solution in Python

class Solution:
  def removeNodes(self, head: ListNode | None) -> ListNode | None:
    if not head:
      return None
    head.next = self.removeNodes(head.next)
    return head.next if head.next and head.val < head.next.val else head
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.