Skip to content

Instantly share code, notes, and snippets.

@thekhairul
Created April 8, 2022 05:41
Show Gist options
  • Save thekhairul/f5860bf129b94faad759489614cbcf4c to your computer and use it in GitHub Desktop.
Save thekhairul/f5860bf129b94faad759489614cbcf4c to your computer and use it in GitHub Desktop.
InterviewBit - max distance between indices of an integer array (Python)
def maximumGap(self, A):
# step 0: make a list of touples (value, index) and sort it by value (O(nlogn))
sortedA = sorted(((v, i) for i, v in enumerate(A)))
# step 1: init maxGap to store maximum gap between 2 indices
# and minNum to store the minimum index so far in the loop
maxGap = 0
minNum = sortedA[0][1]
#step 2: loop through sortedA to find maximum index gap (O(n))
for i in range(1,len(sortedA)):
if sortedA[i][1] < minNum:
minNum = sortedA[i][1]
else:
maxGap = max(maxGap, sortedA[i][1] - minNum) # O(n)
return maxGap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment