Problem 243324 · medium · Level 02 Linear Data Structures

Drop Nodes Shadowed From the Right

linked list · reversal · running maximum

Given the head of a singly linked list, remove every node that has a strictly greater value somewhere to its right, and return the head. The remaining nodes keep their order; the result is always non-increasing from left to right.

Examples

Input:  head = 4 -> 11 -> 6 -> 9 -> 2 -> 7
Output: 11 -> 9 -> 7
Explanation: 4 has 11 to its right, 6 has 9 and 2 has 7.

Input:  head = 6 -> 6 -> 2 -> 6
Output: 6 -> 6 -> 6
Explanation: an equal value to the right does not remove a node.

Constraints

  • 0 <= number of nodes <= 10**4
  • Target: O(n) time; O(1) extra space is possible

Goals

  • Turn a look-ahead condition into a look-behind one by reversing
  • Filter a list against a running maximum
Starting Python…