Reorganize Array Elements by Hash-Based Bucket Assignment
Arrays & HashingAuto-graded · 18 test casesLast 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:
- The rearranged array with elements grouped by bucket
- A list of bucket offsets, where
offsets[i]is the index in the output array where bucketibegins
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^61 ≤ 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
nif 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires a three-pass algorithm to reorganize elements by bucket assignment:
Pass 1: Counting. Iterate through the input and count how many elements belong to each bucket. This gives us the size of each bucket.
Pass 2: Prefix Sum. Convert the bucket counts into starting offsets. The offset for bucket i is the sum of all bucket sizes before it. Bucket 0 starts at index 0, bucket 1 starts at counts[0], bucket 2 starts at counts[0] + counts[1], and so on.
Pass 3: Scattering. Iterate through the input again, placing each element at the next available position in its bucket. We maintain a write pointer for each bucket, initialized to that bucket's offset, and increment it after each write.
This approach correctly handles:
- Empty buckets: Their offset equals the offset of the next bucket (or the array length if all remaining buckets are empty), since the prefix sum naturally accounts for zero counts.
- Negative keys: Python's modulo operation already maps negative keys to valid bucket indices.
- Arbitrary distributions: No assumption is made about the uniformity of bucket assignments.
Complexity
Time Complexity: O(n + b) where n is the number of keys and b is the number of buckets. We make two passes over the keys (O(n) each) and one pass to compute offsets (O(b)).
Space Complexity: O(n + b) for the output array, bucket counts, offsets, and write pointers.
Solution Code
from typing import List, Tuple
def reorganize_by_buckets(keys: List[int], num_buckets: int) -> Tuple[List[int], List[int]]:
if num_buckets <= 0:
raise ValueError("num_buckets must be positive")
# Pass 1: Count elements per bucket
bucket_counts = [0] * num_buckets
for key in keys:
bucket_counts[key % num_buckets] += 1
# Pass 2: Compute offsets via prefix sum
offsets = [0] * num_buckets
for i in range(1, num_buckets):
offsets[i] = offsets[i - 1] + bucket_counts[i - 1]
# Pass 3: Scatter elements to their buckets
next_position = offsets[:]
output = [0] * len(keys)
for key in keys:
bucket = key % num_buckets
output[next_position[bucket]] = key
next_position[bucket] += 1
return output, offsets