Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find minimum possible difference of indices of adjacent elements in Python
Given a list of numbers, two numbers nums[i] and nums[j] are considered adjacent when there is no number with a value between them in the original list. We need to find the minimum possible difference of indices |j - i| such that nums[j] and nums[i] are adjacent.
For example, if the input is nums = [1, -9, 6, -6, 2], the output will be 2, as we can see that 2 and 6 are adjacent elements (no value between 2 and 6 exists in the list) and they are 2 indices apart.
Algorithm Approach
To solve this problem, we will follow these steps ?
Create a map to store indices of each unique value
For identical values, find minimum distance between their indices
For different adjacent values, use two pointers to find minimum distance
Return the overall minimum distance found
Implementation
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)
# Check distance between same values
for row in indexes.values():
for i in range(len(row) - 1):
ans = min(ans, row[i + 1] - row[i])
# Check distance between adjacent different values
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
# Test the solution
ob = Solution()
nums = [1, -9, 6, -6, 2]
print("Input:", nums)
print("Output:", ob.solve(nums))
Input: [1, -9, 6, -6, 2] Output: 2
How It Works
The algorithm works in two phases ?
Phase 1: For identical values, we find the minimum distance between their indices since identical values are always adjacent
Phase 2: For different values that are adjacent (consecutive in sorted order), we use a two-pointer technique to efficiently find the minimum distance between all pairs of indices
In the example [1, -9, 6, -6, 2], the sorted unique values are [-9, -6, 1, 2, 6]. The adjacent pairs are (-9, -6), (-6, 1), (1, 2), and (2, 6). The minimum distance is found between values 2 (at index 4) and 6 (at index 2), giving us |4 - 2| = 2.
Conclusion
This solution efficiently finds the minimum index difference between adjacent elements using a combination of indexing and two-pointer technique. The time complexity is O(n log n) due to sorting, where n is the length of the input array.
