KatInterview

Reorganize Array Elements by Hash-Based Bucket Assignment

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingcountingprefix-sumpartitioning

Last updated

Tests understanding of parallel counting, prefix sums, and scatter operations to group array elements into contiguous buckets.

You need to reorganize an array of integers into buckets based on a simple hash function, then report where each bucket begins in the output.

Given an array keys containing n integers and a positive integer num_buckets, assign each element to a bucket using the rule: bucket_id = key % num_buckets. Rearrange the elements so that all elements belonging to bucket 0 appear first, followed by all elements in bucket 1, and so on through bucket num_buckets - 1.

Return a tuple containing:

  1. The rearranged array with elements grouped by bucket
  2. A list of bucket offsets, where offsets[i] is the index in the output array where bucket i begins

The relative order of elements within the same bucket does not need to be preserved.

For negative keys, the modulo operation follows Python semantics: -1 % 3 = 2, -4 % 4 = 0.

Example:

keys = [12, 7, 3, 8, 5, 10, 1]
num_buckets = 3

Bucket assignments:
12 % 3 = 0
7 % 3 = 1
3 % 3 = 0
8 % 3 = 2
5 % 3 = 2
10 % 3 = 1
1 % 3 = 1

Bucket sizes: [2, 3, 2]
Offsets: [0, 2, 5]

One valid output: ([12, 3, 7, 10, 1, 8, 5], [0, 2, 5])

Constraints:

  • 0 ≤ n ≤ 10^6
  • 1 ≤ num_buckets ≤ 10^4
  • -10^9 ≤ keys[i] ≤ 10^9
  • If a bucket is empty, its offset equals the offset of the next non-empty bucket (or n if all subsequent buckets are empty)

Examples

Example 1

Input: reorganize_by_buckets([12, 7, 3, 8, 5, 10, 1], 3)

Output: [[12, 3, 7, 10, 1, 8, 5], [0, 2, 5]]

Example 2

Input: reorganize_by_buckets([0, 1, 2, 3, 4, 5], 3)

Output: [[0, 3, 1, 4, 2, 5], [0, 2, 4]]

Example 3

Input: reorganize_by_buckets([5, -1, 8, -4, 2], 4)

Output: [[8, -4, 5, 2, -1], [0, 2, 3, 4]]

Hints

Hint 1

Count how many elements belong to each bucket first, then compute where each bucket should start in the output array.

Hint 2

Use a prefix sum on the bucket counts to determine the starting offset for each bucket.

Hint 3

Track the next available position for each bucket as you place elements into the output array.