Minimum Absolute Difference Between Two Values Problem
Description
LeetCode Problem 3880.
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 <= 1000 <= nums[i] <= 2
Solution
Approach: Single Pass
Keep an array last with the most recent index of each value. While scanning nums, for every non-zero x at index i, the closest earlier partner is the last seen value 3 - x (a 2 for a 1, and a 1 for a 2). Update ans = min(ans, i - last[3 - x]), then set last[x] = i. Scanning left to right in this way covers pairs in both orders.
Start ans at n + 1 and fill last with -(n + 1), so a missing partner gives a difference larger than n. At the end, return -1 if ans > n, otherwise ans.
Complexity: time O(n), space O(1), where n is the length of nums.
class Solution:
def minAbsoluteDifference(self, nums: List[int]) -> int:
n = len(nums)
ans = n + 1
last = [-n - 1] * 3
for i, x in enumerate(nums):
if x:
ans = min(ans, i - last[3 - x])
last[x] = i
return -1 if ans > n else ans