<script>
let MaxValue = 2147483647;
function
balanced(small, caps)
{
for
(let i = 0; i < 26; i++)
{
if
(small[i] != 0 && (caps[i] == 0))
return
false
;
else
if
((small[i] == 0) && (caps[i] != 0))
return
false
;
}
return
true
;
}
function
smallestBalancedSubstring(s)
{
let small =
new
Array(26);
let i;
let caps =
new
Array(26);
small.fill(0);
caps.fill(0);
for
(i = 0; i < s.length; i++)
{
if
(s[i].charCodeAt() >= 65 && s[i].charCodeAt() <= 90)
caps[s[i].charCodeAt() - 65]++;
else
small[s[i].charCodeAt()- 97]++;
}
let mp =
new
Map();
for
(i = 0; i < 26; i++)
{
if
(small[i] != 0 && caps[i] == 0){
mp.set(String.fromCharCode(i+97), 1);
}
else
if
(caps[i] != 0 && small[i] == 0)
mp.set(String.fromCharCode(i+65), 1);
}
small.fill(0);
caps.fill(0);
i = 0;
let st = 0;
let start = -1, end = -1;
let minm = MaxValue;
while
(i < s.length)
{
if
(mp.has(s[i]))
{
while
(st < i)
{
if
(s[st].charCodeAt() >= 65 &&
s[st].charCodeAt() <= 90)
caps[s[st].charCodeAt() - 65]--;
else
small[s[st].charCodeAt() - 97]--;
st++;
}
i += 1;
st = i;
}
else
{
if
(s[i].charCodeAt() >= 65 && s[i].charCodeAt() <= 90)
caps[s[i].charCodeAt() - 65]++;
else
small[s[i].charCodeAt() - 97]++;
while
(
true
)
{
if
(s[st].charCodeAt() >= 65 &&
s[st].charCodeAt() <= 90 &&
caps[s[st].charCodeAt() - 65] > 1)
{
caps[s[st].charCodeAt() - 65]--;
st++;
}
else
if
(s[st].charCodeAt() >= 97 &&
s[st].charCodeAt() <= 122 &&
small[s[st].charCodeAt() - 97] > 1)
{
small[s[st].charCodeAt() - 97]--;
st++;
}
else
break
;
}
if
(balanced(small, caps))
{
if
(minm > (i - st + 1))
{
minm = i - st + 1;
start = st;
end = i;
}
}
i += 1;
}
}
if
(start == -1 || end == -1)
document.write(-1 +
"</br>"
);
else
{
let ans =
""
;
for
(let j = start; j <= end; j++)
ans += s[j];
document.write(ans +
"</br>"
);
}
}
let s =
"azABaabba"
;
smallestBalancedSubstring(s);
</script>