Skip to main content

Minimum Absolute Difference Between Two Values - Solution & Explanation

EasyArrayEnumeration7 min readAsked at: Snowflake
Practice this problem

Problem Statement

You are given an integer array nums consisting only of 0, 1, and 2.

A pair of indices (i, j) is called valid if nums[i] == 1 and nums[j] == 2.

Return the minimum absolute difference between i and j among all valid pairs. If no valid pair exists, return -1.

The absolute difference between indices i and j is defined as abs(i - j).

 

Example 1:

Input: nums = [1,0,0,2,0,1]

Output: 2

Explanation:

The valid pairs are:

  • (0, 3) which has absolute difference of abs(0 - 3) = 3.
  • (5, 3) which has absolute difference of abs(5 - 3) = 2.

Thus, the answer is 2.

Example 2:

Input: nums = [1,0,1,0]

Output: -1

Explanation:

There are no valid pairs in the array, thus the answer is -1.

 

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 2

Approach Overview

Problem Overview: Given a list of numbers, you need the smallest absolute difference between any pair of values. The task is simply to find two elements a and b such that |a - b| is minimized.

Approach 1: Brute Force (O(n²) time, O(1) space)

The straightforward method checks every pair of elements. Use two nested loops, compute abs(nums[i] - nums[j]) for all i < j, and track the minimum difference found. This guarantees the correct result but performs n*(n-1)/2 comparisons, which becomes expensive as the array grows. The approach works for small inputs and helps verify correctness during early implementation.

Approach 2: Sort + Single Pass (O(n log n) time, O(1) extra space)

A key observation: the smallest absolute difference must occur between two numbers that are closest in sorted order. After sorting the array, iterate once and compute the difference between adjacent elements only. Maintain a running minimum while scanning from left to right. Sorting takes O(n log n), and the single pass afterward takes O(n), giving an overall complexity of O(n log n) with constant extra space if sorting is done in place.

This approach relies on properties of ordered values: if a ≤ b ≤ c, then |a - c| cannot be smaller than both |a - b| and |b - c|. Because of that, checking only adjacent elements is sufficient.

Problems like this often appear in interviews when discussing arrays and sorting. The optimized method also reflects a common pattern: transform the data structure (sorting) so the final computation becomes a simple linear scan, similar to techniques used in greedy strategies.

Recommended for interviews: Interviewers expect the sort + single pass solution. Starting with brute force demonstrates that you understand the definition of the problem. Moving to the sorted scan shows you can reduce comparisons by exploiting ordering, which is the key insight.

Solution

We use an array last of length 3 to record the last occurrence index of digits 0, 1, and 2. Initially, last = [-(n+1), -(n+1), -(n+1)]. We iterate through the array nums. For the current number x, if x is not equal to 0, we update the answer ans = min(ans, i - last[3 - x]), where i is the index of the current number x. Then we update last[x] = i.

After the iteration, if ans is greater than the length of the array nums, it means no valid index pair exists, so we return -1; otherwise, we return ans.

The time complexity is O(n), where n is the length of the array nums. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Pair ComparisonO(n²)O(1)Small arrays or quick correctness checks
Sort + Single PassO(n log n)O(1)General case and interview‑expected solution

Video Solution

3880. Minimum Absolute Difference Between Two Values (Leetcode Easy)Programming Live with Larry110 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Minimum Absolute Difference Between Two Values easy or hard?
Minimum Absolute Difference Between Two Values is generally considered an easy problem. The key insight is recognizing that sorting allows you to compare only neighboring elements instead of all possible pairs.
Minimum Absolute Difference Between Two Values Python/Java solution
Most implementations follow the same pattern: sort the array, iterate once, and compute the difference between adjacent values. This logic translates directly to Python, Java, C++, Go, and TypeScript with identical time complexity of O(n log n).
How to solve Minimum Absolute Difference Between Two Values in O(n)?
If the input is already sorted, the problem can be solved in O(n) time with a single pass. Iterate through the array once and compute the absolute difference between consecutive elements while tracking the minimum value.
What is the best approach for Minimum Absolute Difference Between Two Values?
The most efficient approach sorts the array and then performs a single pass comparing adjacent elements. After sorting, the minimum absolute difference must appear between neighboring values. This reduces the search from O(n²) comparisons to O(n log n) time with O(1) extra space.
Is Minimum Absolute Difference Between Two Values asked at Google/Amazon/Meta?
Variants of this problem appear in interviews at companies like Amazon and Google as part of array and sorting discussions. Interviewers typically expect the candidate to recognize that sorting enables an efficient adjacent comparison strategy.
What data structure is used in Minimum Absolute Difference Between Two Values?
The core structure is an array. The optimized solution relies on sorting the array and then scanning it sequentially. No additional complex data structures are required beyond basic variables to track the current minimum difference.
What is the time complexity of Minimum Absolute Difference Between Two Values?
The optimal solution runs in O(n log n) time due to sorting. After sorting the array, a single linear scan checks the difference between adjacent elements in O(n) time. The brute force method, which compares all pairs, takes O(n²) time.

Ready to solve this problem?

Practice Minimum Absolute Difference Between Two Values with our built-in code editor and test cases.

Practice on FleetCode