Smallest Palindromic Subsequence of Even Length in Range [ L , R ] | Javascript program to find lexicographically smallest palindromic subsequence of even length ; Frequency array for each character ; Preprocess the frequency array calculation ; Frequency array to track each character in position ' i ' ; Calculating prefix sum over this frequency array to get frequency of a character in a range [ L , R ] . ; Util function for palindromic subsequences ; Find frequency of all characters ; For each character find it 's frequency  in range [L, R] ; If frequency in this range is > 1 , then we must take this character , as it will give lexicographically smallest one ; There is no character in range [ L , R ] such that it 's frequency is > 1. ; Return the character 's value ; Function to find lexicographically smallest palindromic subsequence of even length ; Find in the palindromic subsequences ; No such subsequence exists ; Driver Code ; Function calls
var N = 100001 ; var f = Array . from ( Array ( 26 ) , ( ) => Array ( N ) . fill ( 0 ) ) ; function precompute ( s , n ) { for ( var i = 0 ; i < n ; i ++ ) { f [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] [ i ] ++ ; } for ( var i = 0 ; i < 26 ; i ++ ) { for ( var j = 1 ; j < n ; j ++ ) { f [ i ] [ j ] += f [ i ] [ j - 1 ] ; } } } function palindromicSubsequencesUtil ( L , R ) { var c , ok = 0 ; for ( var i = 0 ; i < 26 ; i ++ ) { var cnt = f [ i ] [ R ] ; if ( L > 0 ) cnt -= f [ i ] [ L - 1 ] ; if ( cnt > 1 ) { ok = 1 ; c = i ; break ; } } if ( ok == 0 ) { return - 1 ; } return c ; } function palindromicSubsequences ( Q , l ) { for ( var i = 0 ; i < l ; i ++ ) { var x = palindromicSubsequencesUtil ( Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; if ( x == - 1 ) { document . write ( - 1 + " " ) ; } else { var c = String . fromCharCode ( ' ' . charCodeAt ( 0 ) + x ) ; document . write ( c + c + " " ) ; } } } var str = " " ; var Q = [ [ 0 , 5 ] , [ 1 , 5 ] , [ 1 , 3 ] ] ; var n = str . length ; var l = Q . length ; precompute ( str , n ) ; palindromicSubsequences ( Q , l ) ;