#3880
Minimum Absolute Difference Between Two Values
EasyArrayEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking all pairs, we can keep track of the last seen indices of 1 and 2. This allows us to calculate the minimum difference in a single pass through the array.
⚙️
Algorithm
3 steps- 1Step 1: Initialize variables to store the last seen index of 1 and 2, and a variable for the minimum difference.
- 2Step 2: Iterate through the array; update the last seen index for 1 or 2 when found.
- 3Step 3: Whenever both indices are updated, calculate the absolute difference and update the minimum difference.
solution.py12 lines
1def minAbsDifference(nums):
2 last1, last2, min_diff = -1, -1, float('inf')
3 for i, num in enumerate(nums):
4 if num == 1:
5 last1 = i
6 if last2 != -1:
7 min_diff = min(min_diff, abs(last1 - last2))
8 elif num == 2:
9 last2 = i
10 if last1 != -1:
11 min_diff = min(min_diff, abs(last1 - last2))
12 return min_diff if min_diff != float('inf') else -1ℹ
Complexity note: The complexity is O(n) because we traverse the array only once, maintaining the last seen indices.
- 1Valid pairs require specific values (1 and 2).
- 2Tracking indices reduces unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.