Skip to content

Instantly share code, notes, and snippets.

@samidarko
Created August 30, 2016 15:00
Show Gist options
  • Save samidarko/688261d0b1a907ecf75332d193d8013d to your computer and use it in GitHub Desktop.
Save samidarko/688261d0b1a907ecf75332d193d8013d to your computer and use it in GitHub Desktop.
def cities_by_distance(arr):
result = [None for _ in arr]
temp = [0 for _ in range(len(arr) - 1)]
for i, _ in enumerate(arr):
origin = i
pos = i
hop = 0
while pos != arr[pos]:
if result[pos] is None:
# not explored yet
pos = arr[pos]
hop += 1
else:
# already explored from here
hop += result[pos]
break
if hop > 0:
result[origin] = hop
temp[hop-1] += 1
return temp
assert cities_by_distance([9, 1, 4, 9, 0, 4, 8, 9, 0, 1]) == [1, 3, 2, 3, 0, 0, 0, 0, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment