Javascript Program to Check if it is possible to make array increasing or decreasing by rotating the array
Last Updated :
08 Jun, 2022
Given an array arr[] of N distinct elements, the task is to check if it is possible to make the array increasing or decreasing by rotating the array in any direction.
Examples:
Input: arr[] = {4, 5, 6, 2, 3}
Output: Yes
Array can be rotated as {2, 3, 4, 5, 6}
Input: arr[] = {1, 2, 4, 3, 5}
Output: No
Approach: There are four possibilities:
- If the array is already increasing then the answer is Yes.
- If the array is already decreasing then the answer is Yes.
- If the array can be made increasing, this can be possible if the given array is first increasing up to the maximum element and then decreasing.
- If the array can be made decreasing, this can be possible if the given array is first decreasing up to the minimum element and then increasing.
If it is not possible to make the array increasing or decreasing then print No.
Below is the implementation of the above approach:
Javascript
<script>
function isPossible(a , n) {
if (n <= 2)
return true ;
var flag = 0;
for (i = 0; i < n - 2; i++) {
if (!(a[i] > a[i + 1] && a[i + 1] > a[i + 2])) {
flag = 1;
break ;
}
}
if (flag == 0)
return true ;
flag = 0;
for (i = 0; i < n - 2; i++) {
if (!(a[i] < a[i + 1] && a[i + 1] < a[i + 2])) {
flag = 1;
break ;
}
}
if (flag == 0)
return true ;
var val1 = Number.MAX_VALUE, mini = -1, val2 = Number.MIN_VALUE, maxi = 0;
for (i = 0; i < n; i++) {
if (a[i] < val1) {
mini = i;
val1 = a[i];
}
if (a[i] > val2) {
maxi = i;
val2 = a[i];
}
}
flag = 1;
for (i = 0; i < maxi; i++) {
if (a[i] > a[i + 1]) {
flag = 0;
break ;
}
}
if (flag == 1 && maxi + 1 == mini) {
flag = 1;
for (i = mini; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
flag = 0;
break ;
}
}
if (flag == 1)
return true ;
}
flag = 1;
for (i = 0; i < mini; i++) {
if (a[i] < a[i + 1]) {
flag = 0;
break ;
}
}
if (flag == 1 && maxi - 1 == mini) {
flag = 1;
for (i = maxi; i < n - 1; i++) {
if (a[i] < a[i + 1]) {
flag = 0;
break ;
}
}
if (flag == 1)
return true ;
}
return false ;
}
var a = [ 4, 5, 6, 2, 3 ];
var n = a.length;
if (isPossible(a, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Check if it is possible to make array increasing or decreasing by rotating the array for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...