Program to find minimum possible difference of indices of adjacent elements in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers nums, we can say that two numbers nums[i] ≤ nums[j] are adjacent when there is no number in between (nums[i], nums[j]) in nums. We have to find the minimum possible |j - i| such that nums[j] and nums[i] are adjacent.

So, if the input is like nums = [1, -9, 6, -6, 2], then the output will be 2, as we can see that 2 and 6 are adjacent and they are 2 indices away from each other.

To solve this, we will follow these steps −

  • indexes := a new map

  • for each index i and value x in A, do

    • insert i at the end of indexes[x]

  • ans := size of A

  • for each row in the list of all values of indexes, do

    • for i in range 0 to size of row - 2, do

      • ans := minimum of ans and (row[i + 1] - row[i])

  • vals := sort the list indexes

  • for k in range 0 to size of vals - 2, do

    • r1 := indexes[vals[k]]

    • r2 := indexes[vals[k + 1]]

    • i := j := 0

    • while i < size of r1 and j < size of r2, do

      • ans := minimum of ans and |r1[i] - r2[j]|

      • if r1[i] < r2[j], then

        • i := i + 1

      • otherwise,

        • j := j + 1

  • return ans

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
class Solution:
   def solve(self, A):
      indexes = defaultdict(list)
      for i, x in enumerate(A):
         indexes[x].append(i)
      ans = len(A)
      for row in indexes.values():
         for i in range(len(row) - 1):
            ans = min(ans, row[i + 1] - row[i])
      vals = sorted(indexes)
      for k in range(len(vals) - 1):
         r1 = indexes[vals[k]]
         r2 = indexes[vals[k + 1]]
         i = j = 0
         while i < len(r1) and j < len(r2):
            ans = min(ans, abs(r1[i] - r2[j]))
            if r1[i] < r2[j]:
               i += 1
            else:
               j += 1
      return ans
ob = Solution()
nums = [1, -9, 6, -6, 2]
print(ob.solve(nums))

Input

[1, -9, 6, -6, 2]

Output

2
raja
Published on 21-Dec-2020 18:32:47
Advertisements