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?

This error occurs if you exceed Leetcode's allocated memory space for a submission. Your solution stores every one of the possible 2^n substrings, each of which has at most n characters: O(n * 2^n), which is quite high. You would want to come up with a more efficient solution to pass the test cases.
For learning purposes, here is a well-explained solution in O(n) space and time: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/731639/JavaScript-Clean-Heavily-Commented-Solution.