BackmediumTwo PointersGoogleAmazon

Tome Cache Extractor 33 Solution

Problem Statement

You are tasked with optimizing the data extraction process for a distributed cache system. The system maintains a sorted array of integer values representing cache hit latencies. Your goal is to identify the pair of elements that yields the minimum absolute difference between them. This metric is critical for determining the stability of the cache extraction pipeline.

Given a sorted array of integers, find the two elements that are closest to each other in value. Return the minimum absolute difference between any two distinct elements in the array. If the array contains fewer than two elements, return 0.

The input will always be a non-decreasing sequence of integers. You must design an algorithm that efficiently computes this value without resorting to brute-force pairwise comparisons, leveraging the sorted nature of the input to achieve optimal performance.

Example 1
Input
nums = [1, 5, 10, 15, 20]
Output
4

Explanation: Initialize left pointer at index 0 (value 1) and right pointer at index 1 (value 5). The difference is |1 - 5| = 4. Update the minimum difference to 4. Move the right pointer to index 2 (value 10). The difference is |1 - 10| = 9, which is greater than 4, so the minimum remains 4. Move the right pointer to index 3 (value 15). The difference is |1 - 15| = 14, minimum remains 4. Move the right pointer to index 4 (value 20). The difference is |1 - 20| = 19, minimum remains 4. Now, move the left pointer to index 1 (value 5) and right pointer to index 2 (value 10). The difference is |5 - 10| = 5, minimum remains 4. Continue this process. The pair (15, 20) yields a difference of 5. The pair (10, 15) yields a difference of 5. The minimum difference found is 4, from the pair (1, 5).

Example 2
Input
nums = [1, 2, 3, 4, 5]
Output
1

Explanation: Start with left at 0 (1) and right at 1 (2). Difference is 1. Minimum is 1. Move right to 2 (3). Difference is 2. Minimum remains 1. Move right to 3 (4). Difference is 3. Minimum remains 1. Move right to 4 (5). Difference is 4. Minimum remains 1. Move left to 1 (2) and right to 2 (3). Difference is 1. Minimum remains 1. The minimum difference is 1.

Example 3
Input
nums = [100, 200, 300, 400, 500]
Output
100

Explanation: Left at 0 (100), right at 1 (200). Difference is 100. Minimum is 100. Left at 1 (200), right at 2 (300). Difference is 100. Minimum remains 100. All consecutive pairs have a difference of 100. The minimum difference is 100.

Example 4
Input
nums = [1, 1, 1, 1]
Output
0

Explanation: Left at 0 (1), right at 1 (1). Difference is 0. Minimum is 0. Since the minimum possible difference is 0, the algorithm can terminate early or continue, but the result remains 0.

Constraints

  • 2 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in non-decreasing order
  • The answer is guaranteed to fit in a 32-bit integer
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Tome Cache Extractor 33 — Problem Statement & Solution Guide

Two PointersMediumInward Pointers
TimeO(n)
|
SpaceO(1)

Problem Description

You are tasked with optimizing the data extraction process for a distributed cache system. The system maintains a sorted array of integer values representing cache hit latencies. Your goal is to identify the pair of elements that yields the minimum absolute difference between them. This metric is critical for determining the stability of the cache extraction pipeline.

Given a sorted array of integers, find the two elements that are closest to each other in value. Return the minimum absolute difference between any two distinct elements in the array. If the array contains fewer than two elements, return 0.

The input will always be a non-decreasing sequence of integers. You must design an algorithm that efficiently computes this value without resorting to brute-force pairwise comparisons, leveraging the sorted nature of the input to achieve optimal performance.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Tome Cache Extractor 33"

medium

WHY DOES IT MATTER?

The adjacent‑pair pattern is a cornerstone of two‑pointer techniques on sorted data. Recognizing that the optimal solution lies in local neighborhoods eliminates unnecessary comparisons, turning a potentially quadratic problem into linear time—crucial for systems handling massive logs or latency metrics.

OPTIMIZATION CHALLENGE

The key insight is the monotonic guarantee: sorting imposes a total order that bounds the difference between non‑adjacent elements by the sum of intermediate gaps. By exploiting this, we avoid the combinatorial explosion of pairwise checks.

REAL-WORLD CONNECTION

In distributed caching, latency measurements are often streamed in sorted order (e.g., by timestamp). Detecting the smallest jitter between consecutive measurements mirrors the adjacent‑pair scan, enabling rapid health checks without exhaustive pairwise analysis.

During an interview, write the simple loop first, then immediately justify why checking only arr[i] and arr[i+1] is sufficient. This shows both coding ability and deep algorithmic reasoning.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

When an array is already sorted, the absolute difference between any two elements is minimized when the elements are adjacent. This property stems from the monotonic nature of sorted sequences: for any i < j < k, we have arr[j] - arr[i] ≤ arr[k] - arr[i] and arr[k] - arr[j] ≤ arr[k] - arr[i]. Consequently, scanning only neighboring pairs guarantees that the global minimum difference will be encountered. A naive O(n²) double loop would compare every possible pair, which quickly becomes infeasible for large n (e.g., n = 10⁶) due to quadratic time and potential memory pressure from recursion or auxiliary structures. The optimal paradigm leverages the two‑pointer (or sliding window) technique: a single pass with a pointer i iterating from 0 to n‑2 and comparing arr[i] with arr[i+1]. This reduces the problem to linear time while using O(1) extra space, aligning with the constraints of high‑throughput cache systems where latency matters.

Interview Questions on This Problem

Q1How would you find the minimum absolute difference between any two elements in a sorted array of size up to 10⁶?

Iterate once over the array, compute diff = arr[i+1] - arr[i] for each i, and keep the smallest diff. Since the array is sorted, the minimum must be among adjacent pairs, giving O(n) time and O(1) space.

Q2If the array were unsorted, what would be the most efficient way to solve the same problem?

First sort the array in O(n log n) time, then apply the adjacent‑pair scan described above. Overall complexity becomes O(n log n) time and O(1) extra space (or O(n) if the sort is not in‑place).

Q3Can you extend the solution to return all pairs that achieve the minimum difference, and what would be the impact on complexity?

After finding the minimum diff in the first pass, perform a second linear pass collecting every adjacent pair whose difference equals the minimum. This still runs in O(n) time and O(k) space, where k is the number of qualifying pairs.

Examples

Example 1

Input

nums = [1, 5, 10, 15, 20]

Output

4

Explanation: Initialize left pointer at index 0 (value 1) and right pointer at index 1 (value 5). The difference is |1 - 5| = 4. Update the minimum difference to 4. Move the right pointer to index 2 (value 10). The difference is |1 - 10| = 9, which is greater than 4, so the minimum remains 4. Move the right pointer to index 3 (value 15). The difference is |1 - 15| = 14, minimum remains 4. Move the right pointer to index 4 (value 20). The difference is |1 - 20| = 19, minimum remains 4. Now, move the left pointer to index 1 (value 5) and right pointer to index 2 (value 10). The difference is |5 - 10| = 5, minimum remains 4. Continue this process. The pair (15, 20) yields a difference of 5. The pair (10, 15) yields a difference of 5. The minimum difference found is 4, from the pair (1, 5).

Example 2

Input

nums = [1, 2, 3, 4, 5]

Output

1

Explanation: Start with left at 0 (1) and right at 1 (2). Difference is 1. Minimum is 1. Move right to 2 (3). Difference is 2. Minimum remains 1. Move right to 3 (4). Difference is 3. Minimum remains 1. Move right to 4 (5). Difference is 4. Minimum remains 1. Move left to 1 (2) and right to 2 (3). Difference is 1. Minimum remains 1. The minimum difference is 1.

Example 3

Input

nums = [100, 200, 300, 400, 500]

Output

100

Explanation: Left at 0 (100), right at 1 (200). Difference is 100. Minimum is 100. Left at 1 (200), right at 2 (300). Difference is 100. Minimum remains 100. All consecutive pairs have a difference of 100. The minimum difference is 100.

Example 4

Input

nums = [1, 1, 1, 1]

Output

0

Explanation: Left at 0 (1), right at 1 (1). Difference is 0. Minimum is 0. Since the minimum possible difference is 0, the algorithm can terminate early or continue, but the result remains 0.

Constraints

  • 2 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in non-decreasing order
  • The answer is guaranteed to fit in a 32-bit integer

Optimal Approach & Strategy

Since the array is sorted, iterate once and compare each element with its immediate neighbor, tracking the minimum difference.

Brute Force Approach

Check every possible pair of elements and keep the smallest absolute difference; this requires two nested loops.

Verified Code Solutions

JavaScript Solution
Time: O(n)
/**
 * @param {number[]} nums
 * @return {number}
 */
var minimumDifference = function(nums) {
    const n = nums.length;
    if (n < 2) return 0;
    
    let minDiff = Infinity;
    let left = 0, right = 1;
    
    while (right < n) {
        const diff = nums[right] - nums[left];
        minDiff = Math.min(minDiff, diff);
        left++;
        right++;
    }
    
    return minDiff;
};

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.