Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Mohammed Dh Abbas
My solution / Easier approach

Mohammed Dh Abbas

Jun 29, 2024

import math class Solution: def sort(self, arr): i = j = 0 # find the first out order position element from [left to right] --> for count in range(len(arr)): if count - 1 >= 0 and arr[count] < arr[count - 1]: i = count - 1 break # find the first out order position element from [right to left] <-- end = i - 1 if i >= 0 else 0 for count in range(len(arr) - 1, end, -1): if count + 1 < len(arr) and arr[count] > arr[count + 1]: j = count + 1 break # for example i and j are in the positions below # [-4, -2, 1, 3, 2, 9, 0, -3, 7, 10, 30] # i j # find the min and max elements between i and j inclusive # min = -3, max = 9 == the range is out of order between [-3, 9] min_element = float('inf') max_element = float('-inf') for count in range(i, j + 1): min_element = min(min_element, arr[count]) max_element = max(max_element, arr[count]) # find any element before i that is larger than the min_element. if found move i to the left for count in range(i - 1, -1, -1): if arr[count] > min_element: i = count # find any element after j that is smaller than the max_element. if found move j to the right for count in range(j + 1, len(arr)): if arr[count] < max_element: j = count return 0 if i == j else j - i + 1

0

0

Comments
Comments

On this page