1331. Uniform Bucket Load

Easy1.5 points estimatedBucket SortArrayCountingMaths

A warehouse scale logs package weights, some of which are recorded as signed offsets from a reference weight, in the array nums. To prepare a histogram the weights are poured into k bins of equal width. Let lo be the smallest value and hi the largest value in nums, and let span = hi - lo + 1. A value x goes into bin floor((x - lo) * k / span), using integer division on non-negative numbers.

Return an array of length k where entry b is the number of values that land in bin b, for b = 0 to k - 1. Bins that receive nothing hold 0. The product (x - lo) * k can exceed 32 bits, so compute it in 64-bit arithmetic. Aim for O(n + k) time and O(k) extra space.

Example 1

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

Here lo = 1 and hi = 10, so the width is 10. Values 1, 2, 3 and 4 map to bucket 0 and the value 10 maps to bucket 1.

Example 2

Input:
nums = [5,5,5], k = 3
Output:
[3,0,0]
Explanation:

All values are equal, so the width is 1 and every value lands in bucket 0.

Example 3

Input:
nums = [0,10,20,30], k = 4
Output:
[1,1,1,1]
Explanation:

With width 31 the values map to buckets 0, 1, 2 and 3, one each.

Constraints

  • 1 ≤ n ≤ 1000, where n is the length of nums
  • 1 ≤ k ≤ 100
  • -109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n + k)
Space
O(k)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…