1344. Gap-Limited Groups

Medium3.5 points estimatedBucket SortArrayHash TableSorting

A radio scanner picks up transmissions on integer frequencies stored in the array nums. Two transmissions belong to the same cluster when, listing all frequencies in sorted order, there is a chain of neighbours where each consecutive pair differs by at most gap. A new cluster therefore starts wherever two consecutive sorted frequencies differ by more than gap. Equal frequencies always share a cluster.

Return the number of clusters. Sorting works in O(n log n), but the intended solution runs in expected O(n): hash each value into a bucket of width gap + 1, so a bucket is always inside one cluster and buckets two or more apart never join, then only compare the extremes of neighbouring non-empty buckets. Use 64-bit arithmetic for gap + 1.

Example 1

Input:
nums = [1,5,9,10], gap = 3
Output:
3
Explanation:

After sorting, the differences 4, 4 and 1 show that 5 and 9 start new groups, giving {1}, {5} and {9, 10}.

Example 2

Input:
nums = [4,4,4], gap = 0
Output:
1
Explanation:

All values are equal, so there is a single group even with a gap of 0.

Example 3

Input:
nums = [1,3,5,20,22], gap = 2
Output:
2
Explanation:

The groups are {1, 3, 5} and {20, 22}, because 20 - 5 = 15 exceeds the gap of 2.

Constraints

  • 1 ≤ n ≤ 105, where n is the length of nums
  • 0 ≤ nums[i] ≤ 109
  • 0 ≤ gap ≤ 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)
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…