The Wayback Machine - https://web.archive.org/web/20210128052300/https://www.geeksforgeeks.org/check-if-a-graph-constructed-from-an-array-based-on-given-conditions-consists-of-a-cycle-or-not/
Related Articles

Related Articles

Check if a graph constructed from an array based on given conditions consists of a cycle or not
  • Difficulty Level : Medium
  • Last Updated : 27 Jan, 2021

Given an array arr[] consisting of first N natural numbers, construct a 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if the graph
// constructed from given array
// contains a cycle or not
void isCycleExists(int arr[], int N)
{
    bool valley = 0;
  
    // Traverse the array
    for (int i = 1; i < N; i++) {
  
        // If arr[i] is less than
        // arr[i - 1] and arr[i]
        if (arr[i] < arr[i - 1]
            && arr[i] < arr[i + 1]) {
  
            cout << "Yes" << endl;
            return;
        }
    }
  
    cout << "No";
}
  
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 3, 2, 4, 5 };
  
    // Size of the array
    int N = sizeof(arr)
            / sizeof(arr[0]);
  
    isCycleExists(arr, N);
  
    return 0;
}

chevron_right


Output:

Yes

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :