/** * @param {string} word * @param {number} k * @return {number} */ var…
- User
/**
-
@param {string} word
-
@param {number} k
-
@return {number} */ var countOfSubstrings = function(word, k) { let vowels = new Set(['a', 'e', 'i', 'o', 'u']); let n = word.length; let count = 0;
for (let i = 0; i < n; i++) { let vowelCount = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}; let consonantCount = 0;
for (let j = i; j < n; j++) { if (vowels.has(word[j])) { vowelCount[word[j]]++; } else if (/[a-zA-Z]/.test(word[j])) { consonantCount++; } if (Object.values(vowelCount).every(v => v > 0) && consonantCount === k) { count++; } }}
return count; };
let word = "aeiouxxaebecidu"; let k = 2; let result = countOfSubstrings(word, k); console.log(result);
Time Limit Exceeded 716 / 768 testcases passed Last Executed Input Use Testcase word = Hidden for this testcase during contest. fix this error in the abobe code
-
- Assistant
To address the Time Limit Exceeded (TLE) error in your code, we can optimize the inner loop by adding a condition to break out early when it's no longer possible to find valid substrings starting from the current index
i. Specifically, if theconsonantCountexceedsk, we can break out of the inner loop since any further extension will only increase theconsonantCountbeyond the desired value. This optimization reduces unnecessary iterations and improves the performance.Here’s the optimized code:
/** * @param {string} word * @param {number} k * @return {number} */ var countOfSubstrings = function(word, k) { let vowels = new Set(['a', 'e', 'i', 'o', 'u']); let n = word.length; let count = 0; for (let i = 0; i < n; i++) { let vowelCount = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}; let consonantCount = 0; for (let j = i; j < n; j++) { if (vowels.has(word[j])) { vowelCount[word[j]]++; } else if (/[a-zA-Z]/.test(word[j])) { consonantCount++; } if (consonantCount > k) break; // Add this condition to break early if (Object.values(vowelCount).every(v => v > 0) && consonantCount === k) { count++; } } } return count; }; let word = "aeiouxxaebecidu"; let k = 2; let result = countOfSubstrings(word, k); console.log(result);