Problem 295560 · medium · Phase 02 Linear Data Structures

Split into Non-Decreasing Runs

arrays · nested lists · runs

Given a list of integers nums, split it into the shortest possible sequence of contiguous non-decreasing runs and return them as a list of lists. A new run starts whenever an element is smaller than the one before it.

Examples

Input:  nums = [1, 2, 2, 1, 5, 3]
Output: [[1, 2, 2], [1, 5], [3]]

Input:  nums = [5, 4, 3]
Output: [[5], [4], [3]]

Constraints

  • 0 <= len(nums) <= 10**5
  • An empty input gives [].
  • Return new lists; do not modify nums.
  • Target: O(n) time.

Goals

  • Compare each element with the end of the current run
  • Start a new run exactly when the order breaks
  • Build a list of lists in one pass
Starting Python…