Given an array arr[] consisting of first N natural numbers, construct an undirected graph using the array elements such that for any array element, connect an edge with the next greater element on the left as well as right.
Examples:
Input: arr = {1, 2, 3, 4, 5}
Output: No
Explanation:
It is clear from the below image that final graph will be a tree.

Input: arr[] = {1, 4, 2, 5, 3}
Output: Yes
Naive Approach: The simplest approach is to construct the required graph using the above conditions and check if there exists any cycle of at least length 3 or not. If there exists a cycle, then print “Yes“. Otherwise, print “No“.
Time Complexity: O(N + E), where E is the number of edges.
Auxiliary Space: O(N)
Efficient Approach: The optimal idea is to check if the given permutation is unimodal or non-unimodal, i.e.simply check if there exists any array element with greater adjacent elements on both sides. If found to be true, print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void isCycleExists( int arr[], int N)
{
bool valley = 0;
for ( int i = 1; i < N; i++) {
if (arr[i] < arr[i - 1]
&& arr[i] < arr[i + 1]) {
cout << "Yes" << endl;
return ;
}
}
cout << "No" ;
}
int main()
{
int arr[] = { 1, 3, 2, 4, 5 };
int N = sizeof (arr)
/ sizeof (arr[0]);
isCycleExists(arr, N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void isCycleExists( int [] arr, int N)
{
for ( int i = 1 ; i < N; i++)
{
if (arr[i] < arr[i - 1 ]
&& arr[i] < arr[i + 1 ])
{
System.out.println( "Yes" );
return ;
}
}
System.out.println( "No" );
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 2 , 4 , 5 };
int N = arr.length;
isCycleExists(arr, N);
}
}
|
Python3
def isCycleExists(arr, N):
valley = 0
for i in range ( 1 , N):
if (arr[i] < arr[i - 1 ] and arr[i] < arr[i + 1 ]):
print ( "Yes" )
return
print ( "No" )
if __name__ = = '__main__' :
arr = [ 1 , 3 , 2 , 4 , 5 ]
N = len (arr)
isCycleExists(arr, N)
|
C#
using System;
class GFG
{
static void isCycleExists( int [] arr, int N)
{
for ( int i = 1; i < N; i++)
{
if (arr[i] < arr[i - 1]
&& arr[i] < arr[i + 1])
{
Console.WriteLine( "Yes" );
return ;
}
}
Console.WriteLine( "No" );
}
public static void Main()
{
int [] arr = { 1, 3, 2, 4, 5 };
int N = arr.Length;
isCycleExists(arr, N);
}
}
|
Javascript
<script>
function isCycleExists(arr,N)
{
for (let i = 1; i < N; i++)
{
if (arr[i] < arr[i - 1]
&& arr[i] < arr[i + 1])
{
document.write( "Yes" );
return ;
}
}
document.write( "No" );
}
let arr=[1, 3, 2, 4, 5 ];
let N = arr.length;
isCycleExists(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)