Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions python/p8_pairWhichGivesGivenDifference.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,31 @@
diff = 45

# Start your code from here
def find_pairs_with_difference(arr, diff):
arr.sort() # Sort the arr

p1 = 0
p2 = 1
count = 0
n = len(arr)
pairs = []

while p2 < n and p1 < n:
if arr[p2] - arr[p1] == diff:
count += 1
pairs.append((arr[p1], arr[p2])) # Store the pair
p1 += 1
p2 += 1
elif arr[p2] - arr[p1] > diff:
p1 += 1
else:
p2 += 1

return count, pairs

arr = [18, 49, 86, 12, 41, 32, 56]
diff = 45
result, pairs = find_pairs_with_difference(arr, diff)
print(f"Number of unique pairs with a difference of {diff}: {result}")
print(f"Pairs with a difference of {diff}: {pairs}")