Back to course home
0% completed
Vote For New Content
I believe this is a simpler and more streight forward approach O(N) on avg (maybe O(NllogN) worst?
adi berkowitz
Dec 10, 2024
I have comments in code explaining We basically traverse array left to right and then right to left
And we find the index that should begin the sort at each traversal
import math class Solution: def sort(self, arr): left_pointer = 0 right_pointer = len(arr)-1 index = 0 # Concept # We should traverse left to right tracking the number (left_pointer) # That needs to change while index< len(arr)-1 and left_pointer>=0: # left_pointer follows index until we have to set it back one # (take [1, 2, 5, 3, 7, 10, 9, 12] example) -> Index and left_pointer # Will keep increasing until index/left_ponter = 2 (5). Next index is 3 # This means that 5 onward needs to be sorted (for now) # So we move left_pointer back. # Now we can keep comparing index+1 to left_pointer and move left_pointer back # each time we find a number in array smaller! if arr[left_pointer] <= arr[index+1]: if left_pointer == index: left_pointer +=1 index += 1 else: left_pointer -= 1 # Do the same thing on other direction index = right_pointer while index > 0 and right_pointer <=len(arr)-1: if arr[right_pointer] >= arr[index-1]: if right_pointer == index: right_pointer -=1 index -= 1 else: right_pointer += 1 if right_pointer <= left_pointer: return 0 return right_pointer - (left_pointer+1)
0
0
Comments
Comments
On this page