Description
You are given a string s consisting of lowercase English letters.
A substring of s is called balanced if all distinct characters in the substring appear the same number of times.
Return the length of the longest balanced substring of s.
Example 1:
Input: s = "abbac"
Output: 4
Explanation:
The longest balanced substring is "abba" because both distinct characters 'a' and 'b' each appear exactly 2 times.
Example 2:
Input: s = "zzabccy"
Output: 4
Explanation:
The longest balanced substring is "zabc" because the distinct characters 'z', 'a', 'b', and 'c' each appear exactly 1 time.
Example 3:
Input: s = "aba"
Output: 2
Explanation:
One of the longest balanced substrings is "ab" because both distinct characters 'a' and 'b' each appear exactly 1 time. Another longest balanced substring is "ba".
Constraints:
1 <= s.length <= 1000sconsists of lowercase English letters.
Solutions
This function also finds the longest substring where all characters have the same frequency, but uses a cleaner approach than the first solution. It iterates through all possible starting positions i, and for each starting point, extends a substring to position j while counting character frequencies in a freq array. Rather than manually checking frequencies with nested loops, it uses Array.prototype.every() to elegantly verify that every frequency is either 0 (character not yet seen) or equals the current character's frequency — meaning all present characters appear the same number of times. Whenever this condition is met, it updates res with the substring length. This approach is more readable and typically faster because it avoids the labeled loop jump pattern used in the first solution.
/**
* @param {string} s
* @return {number}
*/
var longestBalanced = function(s) {
const n = s.length;
const aChar = "a".charCodeAt(0);
let res = 0;
for (let i = 0; i < n; i++) {
const freq = new Array(26).fill(0);
for (let j = i; j < n; j++) {
const code = s.charCodeAt(j) - aChar;
freq[code]++;
if (freq.every(val => val === 0 || val === freq[code])) {
res = Math.max(res, j - i + 1);
}
}
}
return res;
};