fork download
  1. # your code goes here res = max(res, i - mp[arr[i]])
  2. # Python Program to find max distance between two occurrences
  3. # in array using hashing
  4.  
  5. def maxDistance(arr):
  6.  
  7. # Stores element to first index mapping
  8. mp = {}
  9. res = 0
  10.  
  11. for i in range(len(arr)):
  12.  
  13. # If this is the first occurrence of the
  14. # element, store its index
  15. if arr[i] not in mp:
  16. mp[arr[i]] = i
  17.  
  18. # Else update max distance
  19. else:
  20. res = max(res, i - mp[arr[i]])
  21.  
  22. return res
  23.  
  24. arr = [1, 1, 2, 2, 2, 1]
  25. print(maxDistance(arr))
  26.  
Success #stdin #stdout 0.08s 14196KB
stdin
Standard input is empty
stdout
5