Problem 243324 · medium · Phase 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 = 5 -> 2 -> 13 -> 3 -> 8
Output: 13 -> 8
Explanation: 5, 2 and 3 all have 13 or 8 somewhere to their right.

Input:  head = 1 -> 1 -> 1 -> 1
Output: 1 -> 1 -> 1 -> 1

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…