[LeetCode] Longest Balanced Substring I

3713. Longest Balanced Substring I

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int longestBalanced(string s) {
int res = 0, n = s.length();
for(int i = 0; i < n; i++) {
int ma = 0, cnt = 0, freq[26]{0,};
for(int j = i; j < n; j++) {
ma = max(ma, ++freq[s[j]-'a']);
if(freq[s[j]-'a'] == 1) cnt++;
if(j - i + 1 == cnt * ma) res = max(res, j - i + 1);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/13/PS/LeetCode/longest-balanced-substring-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.