<script>
let MAX = 256;
let freq;
function
preCalculate(str, n)
{
freq[str[0].charCodeAt()][0] = 1;
for
(let i = 1; i < n; i++) {
let ch = str[i];
for
(let j = 0; j < MAX; j++) {
let charToUpdate = String.fromCharCode(j);
if
(charToUpdate == ch)
freq[j][i] = freq[j][i - 1] + 1;
else
freq[j][i] = freq[j][i - 1];
}
}
}
function
getFrequency(ch, l, r)
{
if
(l == 0)
return
freq[ch.charCodeAt()][r];
else
return
(freq[ch.charCodeAt()][r] - freq[ch.charCodeAt()][l - 1]);
}
function
firstNonRepeating(str, n, l, r)
{
for
(let i = l; i < r; i++) {
let ch = str[i];
if
(getFrequency(ch, l, r) == 1)
return
(
""
+ ch);
}
return
"-1"
;
}
let str =
"GeeksForGeeks"
;
let n = str.length;
let queries = [ [ 0, 3 ], [ 2, 3 ], [ 5, 12 ] ];
let q = queries.length;
freq =
new
Array(MAX);
for
(let i = 0; i < MAX; i++)
{
freq[i] =
new
Array(n);
for
(let j = 0; j < n; j++)
{
freq[i][j] = 0;
}
}
preCalculate(str, n);
for
(let i = 0; i < q; i++) {
document.write(firstNonRepeating(str, n,
queries[i][0],
queries[i][1]) +
"</br>"
);
}
</script>