Skip to content

Instantly share code, notes, and snippets.

@oskar-j
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oskar-j/bf23ad0ee6fb280ef69e to your computer and use it in GitHub Desktop.
Save oskar-j/bf23ad0ee6fb280ef69e to your computer and use it in GitHub Desktop.
Find max distance (highest difference between indexes) in pairs from a Python list
from collections import defaultdict
def get_distance(l):
assert len(l) > 0
return l[-1] - l[0] # takes O(1) time
def solution(A):
distances = defaultdict(list)
for i, item in enumerate(A):
distances[item].append(i) # takes O(n) time
distances = {k:get_distance(v) for k, v in distances.items() if len(v) > 1}
# dict set item takes O(1) in average
return max(distances.values()) if distances else 0
print solution([4, 6, 2, 2, 6, 6, 1]) # should return 4
print solution([1, 2, 3, 4, 5]) # should return 0
print solution([1, 2, 2, 4, 5]) # should return 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment