Problem 237948 · medium · Level 02 Linear Data Structures

Posts Seen From the Right End

arrays · best-so-far · reverse-traversal

A row of fence posts has heights nums, listed from left to right. Standing at the right-hand end and sighting along the row, you can see a post only if it is strictly taller than every post between it and you; call such a post a leader. The last post is always a leader. Return the heights of the leaders in their left-to-right order.

Examples

Input:  nums = [9, 12, 3, 7, 1, 4]
Output: [12, 7, 4]

Input:  nums = [2, 5, 8]
Output: [8]

Constraints

  • 0 <= len(nums) <= 10**5
  • Target: O(n) time.

Goals

  • Traverse from right to left with a running maximum
  • Produce results in the original order despite scanning backwards
Starting Python…