Batching and serving algorithms · Easy

Stable Length-Bucketed Batches

Problem 43 of 50 · Python and NumPy

Problem

Group requests by prompt-length bucket floor((length−1)/bucket_width). Process buckets in ascending order, preserving original request order within each bucket. Split each bucket into batches of at most batch_size without mixing buckets. Return batches of original zero-based request indices.

def length_bucket_batches(lengths, bucket_width, batch_size):

Constraints

  • lengths contains 0..64 positive integers ≤128.
  • 1 ≤ bucket_width,batch_size ≤32. Bucket 0 covers lengths 1..bucket_width inclusive.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  [
    5,
    1,
    4,
    2
  ],
  4,
  2
]
Expected result: [
  [
    1,
    2
  ],
  [
    3
  ],
  [
    0
  ]
]

Lengths 1,4,2 belong to bucket 0 in original index order [1,2,3], then index 0 forms bucket 1.

Example 2

Arguments: [
  [
    4,
    2,
    3,
    1
  ],
  4,
  3
]
Expected result: [
  [
    0,
    1,
    2
  ],
  [
    3
  ]
]

All requests share a bucket, so retain their input order rather than sorting by length.

Sign in to solve this problem

Browse all coding problems · Learn the foundations