LeetCode Courses 3880. Minimum Absolute Difference Between Two Values
LeetCode

3880. Minimum Absolute Difference Between Two Values

We iterate from a nested-loop pair check to a single-pass scan that only remembers the most recent 1 and 2. The "last-seen pointer" pattern crops up everywhere once you spot it.

1 chapter Beginner Written walk-through Updated 19 May 2026 Phil · @FirnoxGames
Free

Free for everyone. No account needed.

Start reading →

What you'll learn

1 3880. Minimum Absolute Difference Between Two Values 📖 13 min read

We iterate from a nested-loop pair check to a single-pass scan that only remembers the most recent 1 and 2. The "last-seen pointer" pattern crops up everywhere once you spot it.

In this chapter
  1. Problem
  2. Brute force
  3. Possible optimisations
  4. Distance to nearest
  5. Optimal solution

Problem

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

Included with this course
📖Written version of every chapter