Minimum Consecutive Gap Frequency
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Sort an array, find the smallest difference between adjacent elements, and count how many consecutive pairs share that difference.
You are given a list of integers. Sort the list in non-decreasing order, then look at every pair of consecutive elements in the sorted list. Each such pair has a difference equal to the larger element minus the smaller. Find the minimum value among all these consecutive differences, and return the number of consecutive pairs whose difference equals that minimum.
Constraints
2 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9
Examples
Example 1
Input: count_min_gap_pairs([4, 2, 1, 3])
Output: 3
Example 2
Input: count_min_gap_pairs([1, 1, 1, 2])
Output: 2
Hints
Hint 1
After sorting, the smallest difference between any two elements always appears between neighbors.
Hint 2
If a ≤ b ≤ c, then c − a = (c − b) + (b − a), which is at least as large as both adjacent gaps, so a non-adjacent pair can never beat both.
Hint 3
You can track the running minimum gap and its frequency in a single pass, resetting the count whenever a strictly smaller gap appears.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
The core insight is that sorting places the closest values next to each other. For any three sorted values a ≤ b ≤ c, the span c − a breaks down as (c − b) + (b − a), which is at least as large as each sub-gap individually. So a non-adjacent pair can never have a smaller difference than one of the adjacent pairs it covers. This means scanning consecutive elements in sorted order is sufficient to find both the minimum gap and how often it occurs.
The implementation uses two passes over the sorted array. The first pass computes the minimum consecutive difference. The second pass counts how many consecutive pairs have a difference equal to that minimum. Both passes are linear, so the overall cost is dominated by the sort.
Time complexity is O(n log n) from sorting, with O(n) for the two scans. Space complexity is O(n) for the sorted copy (reducible to O(1) auxiliary space if in-place sorting is acceptable).
from typing import List
def count_min_gap_pairs(nums: List[int]) -> int:
values = sorted(nums)
min_diff = min(values[i + 1] - values[i] for i in range(len(values) - 1))
return sum(1 for i in range(len(values) - 1) if values[i + 1] - values[i] == min_diff)