1345. Above-Average Gaps
A seismograph logs n tremor magnitudes in the array nums, which may contain negative offsets. Sort the readings in ascending order and look at the n - 1 gaps between neighbouring sorted values. The average gap is (max - min) / (n - 1). Count how many gaps are strictly larger than this average. Equal neighbours form a gap of 0.
Return that count. To avoid fractions, test each gap with the integer inequality gap * (n - 1) > max - min in 64-bit arithmetic. If all values are equal, the answer is 0. Sorting solves it in O(n log n), but the intended solution is O(n): drop the values into n equal-width buckets, remember each bucket's smallest and largest value, and examine only the gaps between consecutive non-empty buckets, since a wide gap can never sit inside one bucket.
Example 1
- Input:
- nums = [1,2,4,10]
- Output:
- 1
- Explanation:
The sorted gaps are 1, 2 and 6 with an average of 3, and only the gap 6 is strictly larger.
Example 2
- Input:
- nums = [7,7,7]
- Output:
- 0
- Explanation:
All values are equal, so every gap is 0 and none is above the average.
Example 3
- Input:
- nums = [1,4,6,9,12]
- Output:
- 3
- Explanation:
The gaps are 3, 2, 3 and 3 with an average of 2.75, so three of them are larger.
Constraints
- 2 ≤ n ≤ 105, where n is the length of
nums - -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)
- Space
- O(n)