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 return 0.
  • Otherwise, let d be the minimum value of |nums[i] - nums[j]| across all index pairs 0 <= i < j < len(nums).
  • Place the elements of nums in non-decreasing order v[0] <= v[1] <= ... <= v[n - 1] (without mutating the caller's list) and return the count of positions 1 <= k < n satisfying v[k] - v[k - 1] == d.
    • When every integer in nums is distinct (d > 0), this equals the total number of unordered pairs (i, j) in nums whose difference equals d.
    • When repeated integers occur (d = 0), an integer appearing m times forms m - 1 consecutive equal pairs in v.

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 nums unmodified.

Step-by-step walkthrough

  1. 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 difference d = min |nums[i] - nums[j]| across distinct positions and the count of consecutive sorted pairs whose gap equals d (returning 0 when 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 is 2, achieved by (1, 3) and (6, 8) (2 pairs).
    • When duplicates appear (d == 0), two conventions show up across interviews for a value repeated m times:
      1. Consecutive neighbors after sorting (m - 1 pairs per repeated value): required by our specification and Example 2 ([6, -2, 6, 10, 6, -2] -> 3).
      2. All index pairs (i, j) with i < j (m * (m - 1) // 2 pairs per repeated value): an alternative combinatorial variant worth keeping ready for live discussions.

    We implement the sorted consecutive-pair sweep first and then show the one-line frequency formula for the combinatorial variant.

  2. Why checking every pair is too slow

    A brute-force nested loop evaluates |nums[i] - nums[j]| for every index pair 0 <= i < j < n:

    • An array of length n has n * (n - 1) / 2 pairs.
    • At n = 10^5, n * (n - 1) / 2 reaches roughly 5 * 10^9 operations — 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.

  3. Key insight: sorting places closest values side by side

    Suppose we sort a copy of nums in 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:

    1. Smallest gap: min_diff always equals v[i] - v[i - 1] for at least one index 1 <= i < n.
    2. 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]) with j >= i + 2 can never tie min_diff, because v[i + 1] lies strictly between them and would have v[i + 1] - v[i] < v[j] - v[i] = min_diff. Every closest pair is consecutive in sorted_nums.
  4. Find the minimum gap and count matches in one pass

    Rather than scanning sorted_nums once for min_diff and scanning a second time to count ties, we track min_diff and pair_count simultaneously across i = 1 .. len(sorted_nums) - 1:

    • Compute diff = sorted_nums[i] - sorted_nums[i - 1] (guaranteed >= 0 since sorted_nums is non-decreasing).
    • If min_diff is None or diff < min_diff: record the new best min_diff = diff and reset pair_count = 1 so earlier larger gaps are discarded.
    • Else if diff == min_diff: increment pair_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
    
  5. Comparing consecutive pairs vs. all index pairs on duplicates

    Look at the three copies of 6 inside sorted Example 2 ([-2, -2, 6, 6, 6, 10] at sorted indices 2, 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) // 2 for all index pairs? Among m identical copies, there are m choices for the first element and m - 1 remaining choices for the second, and dividing by 2 removes duplicate orderings (a, b) vs (b, a). If an interviewer asks for all index combinations when d == 0, tally frequencies with collections.Counter(nums) and sum m * (m - 1) // 2 across all counts m whenever any m >= 2.

  6. 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: 3
    
  7. Complete 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 in O(n log n) worst-case time and O(n) time on already-ordered lists), and the single neighbor loop performs n - 1 constant-time subtractions and comparisons (O(n)).
  • Space: O(n). sorted(nums) allocates a separate sorted list of n integers 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, returning 1.
  • Fewer than two elements ([] or [42]): Returns 0 immediately via the guard at the top.
  • Smaller gap discovered after tied larger gaps ([15, 1, 9, 5, 14, 13]): Earlier ties at gap 4 are discarded when 14 - 13 = 1 resets pair_count = 1, returning 2.
  • All elements equal ([7, 7, 7, 7, 7]): min_diff = 0 across all n - 1 = 4 consecutive pairs.
  • Multiple duplicate groups ([6, -2, 6, 10, 6, -2]): Sorts to [-2, -2, 6, 6, 6, 10], summing (2 - 1) + (3 - 1) = 3 zero-gap neighbor pairs.
  • Extreme signed values ([-10^9, 10^9]): 10^9 - (-10^9) = 2 * 10^9 is 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, initializing min_diff = 0 makes every duplicate-free input (where min_diff >= 1) return 0. Start min_diff = None (or float("inf")).
  • Forgetting pair_count = 1 when diff < min_diff: Whenever a strictly smaller gap appears, counts accumulated for wider gaps must be thrown away.
  • Mutating nums with nums.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 combinations i < j yield 1 + 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. Same O(n log n) time and O(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_diff is immediately 0 in O(n) average time without sorting — returning n - len(freq) for consecutive sorted pairs (or sum(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_pairs list beside min_diff: set closest_pairs = [(sorted_nums[i - 1], sorted_nums[i])] whenever diff < min_diff, and append (sorted_nums[i - 1], sorted_nums[i]) whenever diff == min_diff. Since at most n - 1 consecutive 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 + 1 and reconstructs the ordered values in one pass). Counting sort runs in O(n + W) time and O(W) space, which simplifies to O(n) linear time when W <= 10^5, followed by the same O(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 for u unique integers (up to O(n) with higher per-bucket memory overhead than a dense list) and still requires sorting those u keys whenever min_diff > 0 because hash tables store keys in arbitrary order. Conversely, if modifying nums is permitted, an in-place sort (rearranging items directly inside nums) saves memory: Python's nums.sort() uses at most O(n) merge scratch space, while heapsort (an O(n log n) comparison sort backed by a binary heap, an array-encoded tree where each parent dominates its children) uses O(1) auxiliary space.

Follow-up questions

Similar questions

More Shield Ai interview questions

All 2 Shield Ai questions →