def min_diff_pairs(nums):
"""
Finds pairs of numbers in nums with the minimum absolute difference.
Args:
nums: A list of integers.
Returns:
A list of pairs of indices (i, j) for which nums[i] - nums[j] has the minimum
absolute difference. The pairs are sorted first by i and then by j. Handles
duplicate elements correctly.
"""
sorted_nums = sorted(nums.copy()) # Sort a copy to avoid modifying original list
min_diff = float('inf')
result = []
for i in range(len(sorted_nums) - 1):
diff = abs(sorted_nums[i] - sorted_nums[i + 1])
if diff < min_diff:
min_diff = diff
result = []
if diff == min_diff:
# Find all indices of sorted_nums[i] and sorted_nums[i+1] in the original list
indices_i = [j for j, x in enumerate(nums) if x == sorted_nums[i]]
indices_j = [j for j, x in enumerate(nums) if x == sorted_nums[i + 1]]
# Create pairs of indices from the original list
for ii in indices_i:
for jj in indices_j:
result.append((ii, jj) if ii < jj else (jj, ii))
result.sort() # Sort pairs first by i and then by j
return result
# Example usage:
numbers = [4, 4, 2, 1, 3]
result = min_diff_pairs(numbers)
print(result)
ZGVmIG1pbl9kaWZmX3BhaXJzKG51bXMpOgogICIiIgogIEZpbmRzIHBhaXJzIG9mIG51bWJlcnMgaW4gbnVtcyB3aXRoIHRoZSBtaW5pbXVtIGFic29sdXRlIGRpZmZlcmVuY2UuCgogIEFyZ3M6CiAgICAgIG51bXM6IEEgbGlzdCBvZiBpbnRlZ2Vycy4KCiAgUmV0dXJuczoKICAgICAgQSBsaXN0IG9mIHBhaXJzIG9mIGluZGljZXMgKGksIGopIGZvciB3aGljaCBudW1zW2ldIC0gbnVtc1tqXSBoYXMgdGhlIG1pbmltdW0KICAgICAgYWJzb2x1dGUgZGlmZmVyZW5jZS4gVGhlIHBhaXJzIGFyZSBzb3J0ZWQgZmlyc3QgYnkgaSBhbmQgdGhlbiBieSBqLiBIYW5kbGVzCiAgICAgIGR1cGxpY2F0ZSBlbGVtZW50cyBjb3JyZWN0bHkuCiAgIiIiCgogIHNvcnRlZF9udW1zID0gc29ydGVkKG51bXMuY29weSgpKSAgIyBTb3J0IGEgY29weSB0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