using
System;
class
GFG
{
static
int
MAX = 256;
static
int
[,]freq;
static
void
preCalculate(
string
str,
int
n)
{
freq[(
int
)str[0],0] = 1;
for
(
int
i = 1; i < n; i++)
{
char
ch = str[i];
for
(
int
j = 0; j < MAX; j++)
{
char
charToUpdate = (
char
)j;
if
(charToUpdate == ch)
freq[j, i] = freq[j, i - 1] + 1;
else
freq[j, i] = freq[j, i - 1];
}
}
}
static
int
getFrequency(
char
ch,
int
l,
int
r)
{
if
(l == 0)
return
freq[(
int
)ch, r];
else
return
(freq[(
int
)ch, r] - freq[(
int
)ch, l - 1]);
}
static
String lastNonRepeating(
string
str,
int
n,
int
l,
int
r)
{
for
(
int
i = r; i >= l; i--)
{
char
ch = str[i];
if
(getFrequency(ch, l, r) == 1)
return
(
""
+ ch);
}
return
"-1"
;
}
public
static
void
Main()
{
string
str =
"GeeksForGeeks"
;
int
n = str.Length;
int
[,]queries = { { 2, 9 }, { 2, 3 }, { 0, 12 } };
int
q = queries.Length;
freq =
new
int
[MAX,n];
preCalculate(str, n);
for
(
int
i = 0; i < q; i++)
{
Console.WriteLine(lastNonRepeating(str, n,
queries[i,0],
queries[i,1]));
}
}
}