KatInterview

Minimum Consecutive Gap Frequency

Heaps, Sorting & SearchAuto-graded · 20 test cases
EasyAuto-gradedHeaps, Sorting & Searcharrayssortingcounting

Last 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.