Problem statement: You have given a circular rotated array. Write a program to sort the circular rotated array.
Input (Circular Rotated Array): [3, 4, 5, 1, 2]
Output (Sorted Array): [1, 2, 3, 4, 5]
This question was asked in one of Byju’s coding interviews. Basically, they asked to find the given element in a circular rotated array in order of
To solve this problem, you have to rotate the array and then do the binary search.
Let’s continue with the sorting circular rotated array.
Table of Contents
[3, 4, 5, 1, 2].
[5, 4, 3, 1, 2].
[5, 4, 3, 2, 1].
[1, 2, 3, 4, 5].
You can solve this problem in any programming language of your choice.
In Python, you can reverse the list using extended slice syntax (just one line of code). But, in competitive programming, you will be encouraged to write your own logic.
# function to reverse the array list def reverse_array(arr, start=0, end=0): if end == 0: end = len(arr)-1 while start<=end: temp = arr[start] arr[start] = arr[end] arr[end] = temp start += 1 end -= 1 # function to sort cicular roated array list def sort_circular_rotated_array(arr): index_smallest = 0 for i in range(len(arr)-1): if arr[i]>arr[i+1]: index_smallest = i+1 break reverse_array(arr=arr, end=index_smallest-1) reverse_array(arr=arr, start=index_smallest) reverse_array(arr=arr) return arr arr = [3, 4, 5, 1, 2] print(sort_circular_rotated_array(arr))
[1, 2, 3, 4, 5]
O(n) time to find the smallest element in the array. For reversing array it will take
O(n) times in the worst-case scenario.
We are calling the reverse array function thrice but each element will get displaced twice so the overall complexity of reversing array is
Total complexity is
O(n)+2*O(3) which is equivalent to
O(n). So, the overall time complexity of this algorithm is
We are not creating any new array and all the elements in the array are getting changed in place. So, the space complexity is
O(1) i.e. constant space.
Hope you learned a new trick to sort the circular rotated array and to find the element in the circular rotated array in minimum time.