I was solving a problem in leetcode. The problem was find the length of longest substring. I solved the problem and the code is running perfectly on local machine and when I run the code on leetcode playground. But when I submit the code it shows runtime error with std:bad_alloc.
here is my code
const lengthOfLongestSubstring = (s) => {
const allSubstring = [];
let subIndex = 0;
let count = 0;
while (count < s.length) {
allSubstring.push(s.substring(count, subIndex + 1));
subIndex += 1;
if (subIndex === s.length) {
count += 1;
subIndex = count;
}
}
const valid = [];
allSubstring.forEach((a) => {
let validStr = '';
a.split('').forEach((s, i) => {
if (!validStr.includes(s)) {
validStr += s;
}
});
if (a.includes(validStr))
valid.push(validStr);
});
let longestSubString = '';
valid.forEach((i) => {
if (longestSubString.length < i.length) {
longestSubString = i;
}
});
return longestSubString.length;
}
I'm new at leetcode. I want to know what is wrong in this code?