Construct a graph which does not contain any pair of adjacent nodes with same value | Function that prints the edges of the generated graph ; First print connections stored in store [ ] ; Check if there is more than one occurrence of 1 st unique element ; Print all other occurrence of 1 st unique element with second unique element ; Function to construct the graph such that the every adjacent nodes have different value ; Stores pair of edges formed ; Stores first unique occurrence ; Check for the second unique occurrence ; Store indices of 2 nd unique occurrence ; To check if arr has only 1 unique element or not ; Store the connections of all unique elements with Node 1 ; If value at node ( i + 1 ) is same as value at Node 1 then store its indices ; If count is zero then it 's not  possible to construct the graph ; If more than 1 unique element is present ; Print the edges ; Driver Code ; Given array having node values ; Function Call
function printConnections ( store , ind , ind1 ) { for ( let pr = 0 ; pr < store . length ; pr ++ ) { document . write ( store [ pr ] [ 0 ] + " " + store [ pr ] [ 1 ] + " " ) ; } if ( ind . length != 0 ) { for ( let x = 0 ; x < ind . length ; x ++ ) { document . write ( ind1 + " " + ( ind [ x ] + 1 ) + " " ) ; } } } function constructGraph ( arr , N ) { let ind = [ ] ; let store = [ ] ; let x = arr [ 0 ] ; let count = 0 ; let ind1 = - 1 ; for ( let i = 1 ; i <= N - 1 ; ++ i ) { if ( arr [ i ] != x ) { ind1 = i + 1 ; count ++ ; store . push ( [ 1 , i + 1 ] ) ; } else { ind . push ( i ) ; } } if ( count == 0 ) { document . write ( " " ) ; } else { document . write ( " " + " " ) ; printConnections ( store , ind , ind1 ) ; } } let N = 5 ; let arr = [ ' ' , ' ' , ' ' , ' ' , ' ' ] ; constructGraph ( arr , N ) ;