fork download
  1. def min_diff_pairs(nums):
  2. """
  3. Finds pairs of numbers in nums with the minimum absolute difference.
  4.  
  5. Args:
  6. nums: A list of integers.
  7.  
  8. Returns:
  9. A list of pairs of indices (i, j) for which nums[i] - nums[j] has the minimum
  10. absolute difference. The pairs are sorted first by i and then by j. Handles
  11. duplicate elements correctly.
  12. """
  13.  
  14. sorted_nums = sorted(nums.copy()) # Sort a copy to avoid modifying original list
  15. min_diff = float('inf')
  16. result = []
  17. for i in range(len(sorted_nums) - 1):
  18. diff = abs(sorted_nums[i] - sorted_nums[i + 1])
  19. if diff < min_diff:
  20. min_diff = diff
  21. result = []
  22. if diff == min_diff:
  23. # Find all indices of sorted_nums[i] and sorted_nums[i+1] in the original list
  24. indices_i = [j for j, x in enumerate(nums) if x == sorted_nums[i]]
  25. indices_j = [j for j, x in enumerate(nums) if x == sorted_nums[i + 1]]
  26. # Create pairs of indices from the original list
  27. for ii in indices_i:
  28. for jj in indices_j:
  29. result.append((ii, jj) if ii < jj else (jj, ii))
  30.  
  31. result.sort() # Sort pairs first by i and then by j
  32. return result
  33.  
  34. # Example usage:
  35. numbers = [4, 4, 2, 1, 3]
  36. result = min_diff_pairs(numbers)
  37. print(result)
Success #stdin #stdout 0.04s 9516KB
stdin
Standard input is empty
stdout
[(0, 0), (0, 1), (0, 1), (1, 1)]