Last active
August 29, 2015 14:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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