// C# program to find lexicographically smallest
// palindromic subsequence of even length
using System;
class GFG{
static int N = 100001;
// Frequency array for each character
static int [,]f = new int[26, N];
// Preprocess the frequency array calculation
static void precompute(String s, int n)
{
// Frequency array to track each character
// in position 'i'
for(int i = 0; i < n; i++)
{
f[s[i] - 'a', i]++;
}
// Calculating prefix sum
// over this frequency array
// to get frequency of a character
// in a range [L, R].
for(int i = 0; i < 26; i++)
{
for(int j = 1; j < n; j++)
{
f[i, j] += f[i, j - 1];
}
}
}
// Util function for palindromic subsequences
static int palindromicSubsequencesUtil(int L, int R)
{
int c = 0, ok = 0;
// Find frequency of all characters
for(int i = 0; i < 26; i++)
{
// For each character
// find it's frequency
// in range [L, R]
int cnt = f[i, R];
if (L > 0)
cnt -= f[i, L - 1];
if (cnt > 1)
{
// If frequency in this range is > 1,
// then we must take this character,
// as it will give
// lexicographically smallest one
ok = 1;
c = i;
break;
}
}
// There is no character
// in range [L, R] such
// that it's frequency is > 1.
if (ok == 0)
{
return -1;
}
// Return the character's value
return c;
}
// Function to find lexicographically smallest
// palindromic subsequence of even length
static void palindromicSubsequences(int [,]Q, int l)
{
for(int i = 0; i < l; i++)
{
// Find in the palindromic subsequences
int x = palindromicSubsequencesUtil(Q[i, 0],
Q[i, 1]);
// No such subsequence exists
if (x == -1)
{
Console.Write(-1 + "\n");
}
else
{
char c = (char)('a' + x);
Console.Write((char) c + "" +
(char) c + "\n");
}
}
}
// Driver Code
public static void Main(String[] args)
{
String str = "dbdeke";
int [,]Q = { { 0, 5 },
{ 1, 5 },
{ 1, 3 } };
int n = str.Length;
int l = Q.GetLength(0);
// Function calls
precompute(str, n);
palindromicSubsequences(Q, l);
}
}
// This code is contributed by amal kumar choubey