Problem 232178 · easy · Phase 02 Linear Data Structures

Split a List on a Separator Value

arrays · nested lists · iteration

Given a list nums and a separator value sep, split nums into groups the same way str.split(sep) splits a string: every occurrence of sep ends the current group and starts a new one, and the separators themselves are dropped. Consecutive separators, or a separator at either end, produce empty groups.

Examples

Input:  nums = [1, 2, 0, 3, 0, 0, 4], sep = 0
Output: [[1, 2], [3], [], [4]]

Input:  nums = [0], sep = 0
Output: [[], []]
Explanation: one separator, so two (empty) groups.

Constraints

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

Goals

  • Mirror str.split semantics on a list
  • Start a new group at every separator, including consecutive ones
  • Always produce one more group than the number of separators
Starting Python…