Given an integer array nums and two integers x and y present in it, find the minimum absolute difference between indices of x and y in a single traversal of the array.

For example,

Input:
 
arr = { 1, 3, 5, 4, 8, 2, 4, 3, 6, 5 }
x = 3, y = 2
 
Output: 2
 
Explanation: Element 3 is present at index 1 and 7, and element 2 is present at index 5. Their minimum absolute difference is min(abs(1-5), abs(7-5)) = 2
 
 
Input:
 
arr = { 1, 3, 5, 4, 8, 2, 4, 3, 6, 5 }
x = 2, y = 5
 
Output: 3
 
Explanation: Element 2 is present at index 5, and element 5 is present at index 2 and 9. Their minimum absolute difference is min(abs(5-2), abs(5-9)) = 3

Practice this problem

The idea is to traverse the array and keep track of the last occurrence of x and y.

  1. If the current element is x, find the absolute difference between the current index of x and the index of the last occurrence of y and update the result if required.
  2. If the current element is y, find the absolute difference between the current index of y and the index of the last occurrence of x and update the result if required.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The minimum difference is 3

Java


Download  Run Code

Output:

The minimum difference is 3

Python


Download  Run Code

Output:

The minimum difference is 3

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.