Closest-Value Pair Count in an Array
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement count_pairs_min_absolute_difference(nums) to determine the smallest absolute distance between any two elements at distinct indices of an integer list nums and count how many adjacent sorted pairs achieve that distance.
More concretely:
- If
len(nums) < 2, no two elements exist to form a pair, so return0. - Otherwise, let
dbe the minimum value of|nums[i] - nums[j]|across all index pairs0 <= i < j < len(nums). - Place the elements of
numsin non-decreasing orderv[0] <= v[1] <= ... <= v[n - 1](without mutating the caller's list) and return the count of positions1 <= k < nsatisfyingv[k] - v[k - 1] == d.- When every integer in
numsis distinct (d > 0), this equals the total number of unordered pairs(i, j)innumswhose difference equalsd. - When repeated integers occur (
d = 0), an integer appearingmtimes formsm - 1consecutive equal pairs inv.
- When every integer in
Examples
Example 1
Input:
nums = [11, 3, 8, 6, 16, 1]
Output:
2
Explanation: In non-decreasing order [1, 3, 6, 8, 11, 16], consecutive differences are 2, 3, 2, 3, and 5. The minimum absolute distance is 2, attained by the 2 pairs (1, 3) and (6, 8).
Example 2
Input:
nums = [6, -2, 6, 10, 6, -2]
Output:
3
Explanation: In non-decreasing order [-2, -2, 6, 6, 6, 10], consecutive differences are 0, 8, 0, 0, and 4. The minimum distance is 0, attained 3 times across consecutive neighbors: once by (-2, -2) and twice by (6, 6).
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9- Leave the caller's input list
numsunmodified.
Step-by-step walkthrough
Understand the goal and duplicate convention
Given an integer list
nums(0 <= len(nums) <= 10^5, values in[-10^9, 10^9]), we want the smallest absolute differenced = min |nums[i] - nums[j]|across distinct positions and the count of consecutive sorted pairs whose gap equalsd(returning0when fewer than two elements exist).Note how repeated values behave when
d == 0:- When all integers are distinct (
d > 0), both ways of phrasing "pair count" agree completely: in Example 1 ([11, 3, 8, 6, 16, 1]), the minimum distance is2, achieved by(1, 3)and(6, 8)(2pairs). - When duplicates appear (
d == 0), two conventions show up across interviews for a value repeatedmtimes:- Consecutive neighbors after sorting (
m - 1pairs per repeated value): required by our specification and Example 2 ([6, -2, 6, 10, 6, -2] -> 3). - All index pairs
(i, j)withi < j(m * (m - 1) // 2pairs per repeated value): an alternative combinatorial variant worth keeping ready for live discussions.
- Consecutive neighbors after sorting (
We implement the sorted consecutive-pair sweep first and then show the one-line frequency formula for the combinatorial variant.
- When all integers are distinct (
Why checking every pair is too slow
A brute-force nested loop evaluates
|nums[i] - nums[j]|for every index pair0 <= i < j < n:- An array of length
nhasn * (n - 1) / 2pairs. - At
n = 10^5,n * (n - 1) / 2reaches roughly5 * 10^9operations — orders of magnitude too slow for a one-second budget.
We need a way to avoid comparing values that sit far apart on the number line.
- An array of length
Key insight: sorting places closest values side by side
Suppose we sort a copy of
numsin non-decreasing order:v[0] <= v[1] <= ... <= v[n - 1]. Consider any three sorted values on a number line:Number line: v[i] -------- v[k] ------------ v[j] |<-- gap1 -->|<---- gap2 ----->| |<------- total gap ---------->| total gap = (v[j] - v[i]) = (v[k] - v[i]) + (v[j] - v[k]) >= v[k] - v[i]Skipping across
v[k]can never yield a smaller distance than checking immediate neighbors! That gives two guarantees:- Smallest gap:
min_diffalways equalsv[i] - v[i - 1]for at least one index1 <= i < n. - All closest pairs when
min_diff > 0: When all elements are distinct (v[0] < v[1] < ... < v[n - 1]), a non-adjacent pair(v[i], v[j])withj >= i + 2can never tiemin_diff, becausev[i + 1]lies strictly between them and would havev[i + 1] - v[i] < v[j] - v[i] = min_diff. Every closest pair is consecutive insorted_nums.
- Smallest gap:
Find the minimum gap and count matches in one pass
Rather than scanning
sorted_numsonce formin_diffand scanning a second time to count ties, we trackmin_diffandpair_countsimultaneously acrossi = 1 .. len(sorted_nums) - 1:- Compute
diff = sorted_nums[i] - sorted_nums[i - 1](guaranteed>= 0sincesorted_numsis non-decreasing). - If
min_diff is Noneordiff < min_diff: record the new bestmin_diff = diffand resetpair_count = 1so earlier larger gaps are discarded. - Else if
diff == min_diff: incrementpair_count += 1. - Else (
diff > min_diff): skip it.
from typing import List, Optional def count_pairs_min_absolute_difference(nums: List[int]) -> int: # Fewer than two elements cannot form any pair. if len(nums) < 2: return 0 # Phase 1: Sort a copy in non-decreasing order so the closest values sit side by side # without mutating the caller's input list. sorted_nums = sorted(nums) # min_diff: smallest adjacent gap (sorted_nums[i] - sorted_nums[i - 1]) seen so far, e.g. 2 min_diff: Optional[int] = None # pair_count: number of adjacent sorted pairs achieving `min_diff` pair_count = 0 # Phase 2: Sweep adjacent pairs once, resetting the tally whenever a strictly smaller gap appears. for i in range(1, len(sorted_nums)): # Because `sorted_nums` is non-decreasing, `diff` is guaranteed >= 0 without `abs()`. diff = sorted_nums[i] - sorted_nums[i - 1] if min_diff is None or diff < min_diff: # Found a strictly smaller gap: discard counts from larger gaps and start fresh at 1. min_diff = diff pair_count = 1 elif diff == min_diff: # Tied with the smallest gap seen so far: count this adjacent pair too. pair_count += 1 return pair_count- Compute
Comparing consecutive pairs vs. all index pairs on duplicates
Look at the three copies of
6inside sorted Example 2 ([-2, -2, 6, 6, 6, 10]at sorted indices2, 3, 4):Sorted slice of 6s: [ 6, 6, 6 ] Sorted indices: 2 3 4 Consecutive neighbor pairs (m - 1 = 2): (idx 2, idx 3) and (idx 3, idx 4) All unordered index combinations i < j (m * (m - 1) // 2 = 3 * 2 // 2 = 3): (idx 2, idx 3), (idx 2, idx 4), and (idx 3, idx 4)Why
m * (m - 1) // 2for all index pairs? Amongmidentical copies, there aremchoices for the first element andm - 1remaining choices for the second, and dividing by2removes duplicate orderings(a, b)vs(b, a). If an interviewer asks for all index combinations whend == 0, tally frequencies withcollections.Counter(nums)and summ * (m - 1) // 2across all countsmwhenever anym >= 2.Trace Example 1 and Example 2 step by step
Example 1: nums = [11, 3, 8, 6, 16, 1] sorted_nums = [1, 3, 6, 8, 11, 16] i = 1: diff = 3 - 1 = 2 -> first gap! min_diff = 2, pair_count = 1 (pair (1, 3)) i = 2: diff = 6 - 3 = 3 -> 3 > 2, ignored i = 3: diff = 8 - 6 = 2 -> ties 2! min_diff = 2, pair_count = 2 (pair (6, 8)) i = 4: diff = 11 - 8 = 3 -> 3 > 2, ignored i = 5: diff = 16 - 11 = 5 -> 5 > 2, ignored Return: 2 Example 2: nums = [6, -2, 6, 10, 6, -2] sorted_nums = [-2, -2, 6, 6, 6, 10] i = 1: diff = -2 - (-2) = 0 -> first gap! min_diff = 0, pair_count = 1 ((-2, -2)) i = 2: diff = 6 - (-2) = 8 -> 8 > 0, ignored i = 3: diff = 6 - 6 = 0 -> ties 0! min_diff = 0, pair_count = 2 (first (6, 6)) i = 4: diff = 6 - 6 = 0 -> ties 0! min_diff = 0, pair_count = 3 (second (6, 6)) i = 5: diff = 10 - 6 = 4 -> 4 > 0, ignored Return: 3Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_pairs_min_absolute_difference(nums: List[int]) -> int: # Fewer than two elements cannot form any pair. if len(nums) < 2: return 0 # Phase 1: Sort a copy in non-decreasing order so the closest values sit side by side # without mutating the caller's input list. sorted_nums = sorted(nums) # min_diff: smallest adjacent gap (sorted_nums[i] - sorted_nums[i - 1]) seen so far, e.g. 2 min_diff: Optional[int] = None # pair_count: number of adjacent sorted pairs achieving `min_diff` pair_count = 0 # Phase 2: Sweep adjacent pairs once, resetting the tally whenever a strictly smaller gap appears. for i in range(1, len(sorted_nums)): # Because `sorted_nums` is non-decreasing, `diff` is guaranteed >= 0 without `abs()`. diff = sorted_nums[i] - sorted_nums[i - 1] if min_diff is None or diff < min_diff: # Found a strictly smaller gap: discard counts from larger gaps and start fresh at 1. min_diff = diff pair_count = 1 elif diff == min_diff: # Tied with the smallest gap seen so far: count this adjacent pair too. pair_count += 1 return pair_count✅ Submit now — all tests should pass.
Intuition & how it works
Picture lining people up from shortest to tallest and finding the smallest height difference in the room. Once everyone stands in sorted order, you never need to compare people standing at opposite ends of the line — jumping over anyone in between can only make the absolute difference (|a - b|, the non-negative distance between two values on a number line) larger! Every candidate for the smallest gap sits directly between two consecutive neighbors, so one left-to-right walk down the sorted line finds both the smallest gap and how many unordered pairs (pairs where (a, b) and (b, a) count as the same pair) achieve it.
Why does the naive approach fall short? Inspecting all n * (n - 1) / 2 index pairs in the unsorted input costs O(n^2) time, reaching roughly 5 * 10^9 steps when n = 10^5. Conversely, scanning neighbors without sorting fails because the closest values may sit far apart in nums (in [11, 3, 8, 6, 16, 1], 3 and 1 sit at indices 1 and 5).
Here is how sorting plus one sweep works on Examples 1 and 2:
Example 1: nums = [11, 3, 8, 6, 16, 1]
1. Sort: [1, 3, 6, 8, 11, 16]
2. Consecutive gaps: 2, 3, 2, 3, 5
-> min_diff = 2, achieved by (1, 3) and (6, 8) -> returns 2
Example 2 (duplicates): nums = [6, -2, 6, 10, 6, -2]
1. Sort: [-2, -2, 6, 6, 6, 10]
2. Consecutive gaps: 0, 8, 0, 0, 4
-> min_diff = 0, achieved by 3 consecutive pairs -> returns 3
Complexity
Let n be len(nums).
- Time:
O(n log n).sorted(nums)runs Timsort (Python's hybrid merge-and-insertion sort that runs inO(n log n)worst-case time andO(n)time on already-ordered lists), and the single neighbor loop performsn - 1constant-time subtractions and comparisons (O(n)). - Space:
O(n).sorted(nums)allocates a separate sorted list ofnintegers so the caller's list stays untouched, while the sweep itself maintains only scalar counters (O(1)extra variables).
Edge cases
- Minimum pairable length (
n = 2, e.g.,[5, -5]): Exactly one neighbor gap exists, returning1. - Fewer than two elements (
[]or[42]): Returns0immediately via the guard at the top. - Smaller gap discovered after tied larger gaps (
[15, 1, 9, 5, 14, 13]): Earlier ties at gap4are discarded when14 - 13 = 1resetspair_count = 1, returning2. - All elements equal (
[7, 7, 7, 7, 7]):min_diff = 0across alln - 1 = 4consecutive pairs. - Multiple duplicate groups (
[6, -2, 6, 10, 6, -2]): Sorts to[-2, -2, 6, 6, 6, 10], summing(2 - 1) + (3 - 1) = 3zero-gap neighbor pairs. - Extreme signed values (
[-10^9, 10^9]):10^9 - (-10^9) = 2 * 10^9is exact in Python arbitrary-precision integers (use 64-bit integers in C++/Java to avoid 32-bit overflow).
Common mistakes
- Starting
min_diff = 0: Because absolute distances are never negative, initializingmin_diff = 0makes every duplicate-free input (wheremin_diff >= 1) return0. Startmin_diff = None(orfloat("inf")). - Forgetting
pair_count = 1whendiff < min_diff: Whenever a strictly smaller gap appears, counts accumulated for wider gaps must be thrown away. - Mutating
numswithnums.sort(): Calling.sort()in place alters the caller's list;sorted(nums)sorts a fresh copy. - Mixing up duplicate conventions: On
[6, -2, 6, 10, 6, -2], consecutive sorted pairs yield(2 - 1) + (3 - 1) = 3, whereas all index combinationsi < jyield1 + 3 = 4. Confirm which rule applies whenever duplicates are allowed.
Alternative approaches
- Two-pass scan: Compute
min_diff = min(sorted_nums[i] - sorted_nums[i - 1] for i in range(1, n))first, then count matching indices in a second loop. SameO(n log n)time andO(n)space with one extra linear pass. - Frequency dictionary fast-path: Count occurrences in a hash map (a key-value dictionary providing
O(1)average lookup) first. Whenever any key has count>= 2,min_diffis immediately0inO(n)average time without sorting — returningn - len(freq)for consecutive sorted pairs (orsum(m * (m - 1) // 2 for m in freq.values())for all index pairs). Fall back to sorting only when all elements are unique.
Follow-up questions
- How would your code change if the caller wanted the list of closest pairs themselves instead of only their count? Keep a
closest_pairslist besidemin_diff: setclosest_pairs = [(sorted_nums[i - 1], sorted_nums[i])]wheneverdiff < min_diff, and append(sorted_nums[i - 1], sorted_nums[i])wheneverdiff == min_diff. Since at mostn - 1consecutive pairs exist, runtime (O(n log n)) and space (O(n)) remain unchanged; if original array indices are requested, sort(value, index)tuples instead. - If every element falls inside a bounded integer span of width at most 10^5, how can you achieve O(n) runtime? Use counting sort (a non-comparison sort that tallies each integer's frequency inside an array of length
W = max_val - min_val + 1and reconstructs the ordered values in one pass). Counting sort runs inO(n + W)time andO(W)space, which simplifies toO(n)linear time whenW <= 10^5, followed by the sameO(n)neighbor sweep. - How does auxiliary memory usage compare between building a frequency dictionary and sorting the array? A frequency dictionary allocates
O(u)entries foruunique integers (up toO(n)with higher per-bucket memory overhead than a dense list) and still requires sorting thoseukeys whenevermin_diff > 0because hash tables store keys in arbitrary order. Conversely, if modifyingnumsis permitted, an in-place sort (rearranging items directly insidenums) saves memory: Python'snums.sort()uses at mostO(n)merge scratch space, while heapsort (anO(n log n)comparison sort backed by a binary heap, an array-encoded tree where each parent dominates its children) usesO(1)auxiliary space.
Follow-up questions
- How would your code change if the caller wanted the list of closest pairs themselves instead of only their count?
- If every element falls inside a bounded integer span of width at most 10^5, how can you achieve O(n) runtime?
- How does auxiliary memory usage compare between building a frequency dictionary and sorting the array?
Similar questions
- Multi-Layered Testing Strategy for Autonomous Drone Flight Planning
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One