Longest Balanced Substring I Problem
#3713
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3713.
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.
Solution
Approach: Enumeration + Counting
Try every start i and extend the end j, maintaining the character counts of s[i..j], the maximum count mx and the number of distinct characters v. The substring is balanced exactly when every distinct character appears mx times, that is, when mx * v == j - i + 1. Record the longest such length.
Complexity: O(n^2) time and O(26) extra space.
from collections import Counter
class Solution:
def longestBalanced(self, s: str) -> int:
n = len(s)
ans = 0
for i in range(n):
cnt = Counter()
mx = v = 0
for j in range(i, n):
cnt[s[j]] += 1
mx = max(mx, cnt[s[j]])
if cnt[s[j]] == 1:
v += 1
if mx * v == j - i + 1:
ans = max(ans, j - i + 1)
return ans