Minimum Absolute Difference Between Two Values

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
Inputnums = [1,0,0,2,0,1]
Output2
The valid pairs are (0, 3) with absolute difference 3 and (5, 3) with absolute difference 2, so the answer is 2.
Example 2
Inputnums = [1,0,1,0]
Output-1
There are no valid pairs in the array, so the answer is -1.

Constraints

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

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate