Skip to content

Instantly share code, notes, and snippets.

@agmezr
Created November 29, 2018 21:14
Show Gist options
  • Save agmezr/7112dc40edaa032110dd0a732ded514f to your computer and use it in GitHub Desktop.
Save agmezr/7112dc40edaa032110dd0a732ded514f to your computer and use it in GitHub Desktop.
Find the minimum distance or difference between two sorted list on n + m
def get_min_difference(m, n):
"""
A quick function for finding the min difference between two list (already sorted) on n + m.
Because I always forget about it and end up using n * m
"""
# pointer for m
i = 0
# pointer for n
j = 0
#for default difference
difference = float("inf")
#iterate until one pointer reaches the end
while i < len(m) and j < len(n):
# update min difference
difference = min(difference, abs(m[i] - n[j]))
# increment the lowest value so the gap reduces on next iteration
if m[i] <= n[j]:
i += 1
else:
j += 1
return difference
# test
m = [1,3,5]
n = [2,8,10,12,14]
result = get_min_difference(m, n)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment