Algo-Sim › Sorting & Divide and Conquer
Bucket Sort
Medium · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input
Scatter values into k equal-width buckets, sort each small bucket, and read them back in order: O(n + k) expected when values are spread evenly.
Problem
Sort nums, whose values lie in 0..99, with k buckets. Bucket b takes the values x with ⌊x · k / 100⌋ = b, so every value in a later bucket is larger. Sort each bucket on its own (insertion sort here), then concatenate the buckets.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- 0 ≤ nums[i] < 100 (any known range works after scaling)
- 1 ≤ k ≤ n
- O(n + k) expected for evenly spread values; O(n²) if they all share one bucket
Edge cases to test
- Every value in one bucket (the O(n²) worst case)
- Empty buckets
- Values at the bucket edges (0, 99)
- One element
Follow-up questions
- When is bucket sort linear?
- When the values are spread evenly and k is about n: each bucket holds O(1) values on average, so the sorts cost O(n) in total and the whole run O(n + k).
- Where does the idea come up in interviews?
- Bucketing by a bounded key: Top K Frequent Elements puts values into buckets by frequency (at most n), and Maximum Gap uses n − 1 buckets to beat O(n log n).
Solution
Java
public int[] bucketSort(int[] nums, int k) {
List<List<Integer>> buckets = new ArrayList<>();
for (int b = 0; b < k; b++) buckets.add(new ArrayList<>());
for (int x : nums) buckets.get(x * k / 100).add(x);
int i = 0;
for (List<Integer> bucket : buckets) {
for (int j = 1; j < bucket.size(); j++) {
int x = bucket.get(j), p = j - 1;
while (p >= 0 && bucket.get(p) > x) {
bucket.set(p + 1, bucket.get(p));
p--;
}
bucket.set(p + 1, x);
}
for (int x : bucket) nums[i++] = x;
}
return nums;
}Python
def bucket_sort(nums, k):
buckets = [[] for _ in range(k)]
for x in nums:
buckets[x * k // 100].append(x)
i = 0
for bucket in buckets:
for j in range(1, len(bucket)):
x, p = bucket[j], j - 1
while p >= 0 and bucket[p] > x:
bucket[p + 1] = bucket[p]
p -= 1
bucket[p + 1] = x
for x in bucket:
nums[i] = x
i += 1
return numsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> bucketSort(vector<int> &nums, int k) {
vector<vector<int>> buckets = vector<vector<int>>(k);
for (int x : nums)
buckets[x * k / 100].push_back(x);
int i = 0;
for (vector<int> &bucket : buckets) {
for (int j = 1; j < int(bucket.size()); j++) {
int x = bucket[j], p = j - 1;
while (p >= 0 && bucket[p] > x) {
bucket[p + 1] = bucket[p];
p--;
}
bucket[p + 1] = x;
}
for (int x : bucket)
nums[i++] = x;
}
return nums;
}
};
More Sorting & Divide and Conquer problems
- Bubble Sort (Easy)
- Insertion Sort (Easy)
- Selection Sort (Easy)
- Merge Sort (Medium)
- Quick Sort (Lomuto) (Medium)
- Quick Sort (Hoare) (Medium)
- Counting Sort (Easy)
- Radix Sort (LSD) (Medium)
- Kth Largest Element (Quickselect) (Medium)
- Count Inversions (Hard)
- Largest Number (Medium)