Problem 286749 · easy · Phase 02 Linear Data Structures

Chunk into Fixed-Size Groups

arrays · slicing · nested lists

Given a list nums and a positive integer k, split the list into consecutive groups of k elements and return them as a list of lists. The final group may contain fewer than k elements if the length is not a multiple of k.

Examples

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

Input:  nums = [], k = 3
Output: []

Constraints

  • 0 <= len(nums) <= 10**5
  • 1 <= k <= 10**5
  • Return new lists; do not modify nums.
  • Target: O(n) time.

Goals

  • Step through a list in strides of k
  • Produce a shorter final group instead of padding
  • Return an empty list of groups for empty input
Starting Python…