Problem · Array

Minimum Index Distance Between Two Values

Learn this problem
EasyDream11 logoDream11FULLTIMEONSITE INTERVIEW

Problem statement

Given an integer array nums and two distinct integers x and y that each occur at least once, return the minimum value of |i - j| over all indices where nums[i] = x and nums[j] = y.

Function

minimumIndexDistance(nums: int[], x: int, y: int) → int

Examples

Example 1

nums = [3,5,4,2,6,5,6,6,5,4,8,3]x = 3y = 6return = 4

The closest pair is at indices 0 and 4, whose distance is 4.

Example 2

nums = [1,2,1,2]x = 1y = 2return = 1

Values 1 and 2 appear at adjacent indices.

Constraints

  • 2 <= nums.length <= 10^5.
  • -10^9 <= nums[i], x, y <= 10^9.
  • x != y, and both values occur at least once.

More Dream11 problems

drafts saved locally
public int minimumIndexDistance(int[] nums, int x, int y) {
    // Return the minimum absolute index distance.
}
nums[3,5,4,2,6,5,6,6,5,4,8,3]
x3
y6
expected4
checking account