Suppose we have an array called nums with unique elements. We have to check whether the array will be sorted or not after reversing one sub-array of it. If the array is already sorted, then also return true.
So, if the input is like nums = [4,6,27,25,15,9,37,42], then the output will be True because if we reverse [9,15,25,27], then the array will be sorted.
To solve this, we will follow these steps −
- n := size of nums
- if array has only one element then return True
- i := 1
- for i in range 1 to n - 1, do
- if nums[i - 1] < nums[i], then
- if i is same as n, then return true, otherwise come out from loop
- if nums[i - 1] < nums[i], then
- j := i
- while j < n and nums[j] < nums[j - 1], do
- if i > 1 and nums[j] < nums[i - 2], then return false
- j := j + 1
- if j is same as n, then return True
- k := j
- if nums[k] < nums[i - 1], then return False
- while k > 1 and k < n, do
- if nums[k] < nums[k - 1], then return False
- k := k + 1
- return True
Let us see the following implementation to get better understanding −
Example Code
def solve(nums): n = len(nums) if n == 1: return True i = 1 for i in range(1, n): if nums[i - 1] < nums[i] : if i == n: return True else: break j = i while j < n and nums[j] < nums[j - 1]: if i > 1 and nums[j] < nums[i - 2]: return False j += 1 if j == n: return True k = j if nums[k] < nums[i - 1]: return False while k > 1 and k < n: if nums[k] < nums[k - 1]: return False k += 1 return True nums = [4,6,27,25,15,9,37,42] print(solve(nums))
Input
[4,6,27,25,15,9,37,42]
Output
True