↓Skip to main content
  1. LeetCode/

LeetCode 3713: Longest Balanced Substring I

·2 mins· ·
LeetCode Medium Hash-Table String Counting Enumeration
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-06-22

  • Submissions: Time Limit Exceeded → Accepted (1.9 s)

Approach
#

With n <= 1000, enumerating all substrings is O(n²). Fix the start and extend right, maintaining each character’s count incrementally (String Template 5).

Checking “every character has the same count” does not require comparing all counts: if each appears f times, the length is f × kinds; conversely, if the highest count is f and the length equals f × kinds, every kind must be exactly f. So track max_freq and the number of kinds for an O(1) check per step.

My Attempts
#

Attempt 1 wrapped everything in an extra loop over “number of kinds, 1 to 26”, doing 26 times the work, TLE. Removing it passed, but checking len(set(freq.values())) each step still took 1.9 s.

Solution
#

class Solution:
    def longestBalanced(self, s: str) -> int:
        n, best = len(s), 0
        for i in range(n):
            cnt = Counter()
            max_freq = 0
            for j in range(i, n):
                cnt[s[j]] += 1
                max_freq = max(max_freq, cnt[s[j]])
                if max_freq * len(cnt) == j - i + 1:
                    best = max(best, j - i + 1)
        return best

Complexity
#

Time O(n²), space O(1) (at most 26 characters).

Mistakes to Avoid
#

  • Do not add an unnecessary layer of enumeration.
  • Building a set of counts each step is O(26); “highest count × kinds = length” is O(1).

Interview Explanation
#

I fix the start and extend right, tracking counts, the highest count, and the number of kinds. All counts are equal exactly when the highest count times the number of kinds equals the length, an O(1) check per step, O(n²) overall.

Related

LeetCode 3839: Number of Prefix Connected Groups
·1 min
LeetCode Medium Hash-Table String Counting
LeetCode 3839 note: words sharing the first k characters are connected, so count by word[:k]; exclude words shorter than k
LeetCode 2131: Longest Palindrome by Concatenating Two Letter Words
·2 mins
LeetCode Medium Greedy Hash-Table String Counting
LeetCode 2131 note: pair each word with its reverse on both sides; self-palindromes also pair with each other, and only one leftover can sit in the middle
LeetCode 3805: Count Caesar Cipher Pairs
·2 mins
LeetCode Medium Math Hash-Table String Counting
LeetCode 3805 note: shift each string so its first letter is a, making Caesar-equivalent strings identical, then count pairs per normalized form
LeetCode 3960: Frequency Balance Subarray
·2 mins
LeetCode Medium Hash-Table Counting Array
LeetCode 3960 note: n is only 1000, so fix the left end and extend right while maintaining value -> count and count -> how many; exactly two counts f and 2f means balanced
LeetCode 3900: Longest Balanced Substring After One Swap
·3 mins
LeetCode Medium Prefix-Sum Hash-Table String
LeetCode 3900 note: equal prefix differences mean balanced; a substring off by 2 also works if a swappable character exists outside, and keeping the two earliest positions per difference is enough
LeetCode 244: Shortest Word Distance II
·2 mins
LeetCode Medium Two-Pointers Design Hash-Table String Array
LeetCode 244 note: precompute each word’s positions (sorted by construction), then answer each query by merging the two position lists with two pointers, always advancing the smaller one