1234. Gap Histogram

Easy1.5 points estimatedHash TableSortingCounting3 hints

A weather station logs integer pressure readings, and an analyst wants to know how evenly spaced the distinct readings are. Take the array nums, keep each distinct value once and sort those values ascending. The gaps are the differences between each pair of neighbouring values in that sorted list.

Return a map from each gap size to the number of times that gap occurs. If there are fewer than two distinct values there are no gaps and the map is empty. Duplicate readings never create a gap of size zero. The order of the keys in the returned map does not matter.

The intended solution sorts the distinct values and tallies the gaps in a hash map, running in O(n log n) time and O(n) space.

Example 1

Input:
nums = [44,-3,14,14,25,-3,66,36,47,3]
Output:
{"11":3,"19":1,"3":1,"6":1,"8":1}
Explanation:

The distinct sorted values are -3, 3, 14, 25, 36, 44, 47, 66, so the gaps are 6, 11, 11, 11, 8, 3 and 19, which makes the gap 11 occur three times.

Example 2

Input:
nums = [18,18,200,-77,-77,41,0]
Output:
{"159":1,"18":1,"23":1,"77":1}
Explanation:

The distinct sorted values are -77, 0, 18, 41, 200, so the four gaps are 77, 18, 23 and 159, each occurring once.

Constraints

1 ≤ nums.length ≤ 1000

-106 ≤ nums[i] ≤ 106

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n log n)
Space
O(n)

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…