Remove Nodes From Linked List

Medium Topics Company Tags

Remove every node that has a strictly greater value somewhere after it in the singly linked list. Return the head of the remaining list, preserving the original order of the surviving nodes. An equal value to the right does not cause removal. Input and output arrays list node values from head to tail.

Example 1:

Remove Nodes From Linked List, example 1: illustration of the example

Input: head = [4,7,3,6,2]

Output: [7,6,2]

Explanation: Remove 4 because 7 is later, and remove 3 because 6 is later. The surviving nodes form 7 -> 6 -> 2.

Example 2:

Remove Nodes From Linked List, example 2: illustration of the example

Input: head = [5,5,3,3]

Output: [5,5,3,3]

Explanation: No node has a strictly greater value to its right. Equal later values do not count, so every node remains.

Example 3:

Remove Nodes From Linked List, example 3: illustration of the example

Input: head = [1,2,3,4]

Output: [4]

Explanation: Each of the first three nodes has a greater value later in the list. Only the final node, containing 4, remains.

Constraints:

  • The list contains between 1 and 100000 nodes.
  • 1 <= Node.val <= 100000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.