Skip to main content

Longest Balanced Substring II - Solution & Explanation

MediumHash TableStringPrefix Sum17 min readAsked at: Amazon, Microsoft, Meta +3
Practice this problem

Problem Statement

You are given a string s consisting only of the characters 'a', 'b', and 'c'.

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 = "aabcc"

Output: 3

Explanation:

The longest balanced substring is "abc" because all distinct characters '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 <= 105
  • s contains only the characters 'a', 'b', and 'c'.

Approach Overview

Problem Overview: You are given a string and must find the length of the longest substring that is balanced. A substring is balanced when two categories of characters appear in equal count. The goal is to scan the string and efficiently detect the largest range where this balance condition holds.

Approach 1: Enumeration (Brute Force) (Time: O(n^2), Space: O(1))

The most direct strategy checks every possible substring. Start each substring at index i, expand to j, and maintain counters for the two character groups. Each time the counts become equal, update the maximum length. This works because every candidate substring is evaluated exactly once. The drawback is the quadratic runtime: for a string of length n, there are O(n^2) substrings to examine. This approach helps you reason about the balance condition but quickly becomes too slow for large inputs.

Approach 2: Enumeration + Prefix Sum + Hash Table (Time: O(n), Space: O(n))

The optimal method converts the balance condition into a prefix sum problem. Map one character category to +1 and the other to -1. As you iterate through the string, maintain a running prefix sum representing the difference between the two counts. When the same prefix value appears at two indices, the substring between them has equal numbers of both characters because the net difference cancels out.

Use a hash table to store the earliest index where each prefix sum occurs. When you encounter the same prefix sum again, compute the candidate length current_index - first_index. Keep the maximum across the scan. This reduces the problem to a single pass with constant-time hash lookups. The technique is a classic application of Prefix Sum combined with a Hash Table to track previously seen states. The string is processed once, giving O(n) time complexity and O(n) additional space.

This pattern appears frequently in substring problems where equality or balance constraints exist. Instead of recomputing counts for every substring, the prefix difference encodes the state of the scan, and repeated states reveal balanced ranges automatically. Similar ideas also appear in other String scanning problems involving equal frequency or net-zero conditions.

Recommended for interviews: Start by describing the brute force enumeration to demonstrate understanding of the balance definition. Then move to the prefix sum + hash table optimization. Interviewers typically expect the O(n) solution because it shows you recognize the "same prefix state implies balanced subarray" pattern and can implement it efficiently with a hash map.

Solution

The answer is divided into the following three cases:

  1. Balanced substring with only one character, such as "aaa".
  2. Balanced substring with two characters, such as "aabb".
  3. Balanced substring with three characters, such as "abc".

We define three functions calc1(s), calc2(s, a, b), and calc3(s) to calculate the longest balanced substring length for the above three cases respectively, and finally return the maximum of the three.

For calc1(s), we only need to traverse the string s, count the length of each consecutive character, and take the maximum value.

For calc2(s, a, b), we can use prefix sum and hash table to calculate the longest balanced substring length. Specifically, we maintain a variable d to represent the number of character a minus the number of character b in the current substring, and use a hash table to record the first occurrence position of each d value. When we encounter the same d value again, it means that the number of character a and character b in the substring from the last occurrence position to the current position are equal, i.e., the substring is balanced, and we update the answer.

For calc3(s), we also use prefix sum and hash table to calculate the longest balanced substring length. We define an array cnt to record the counts of characters a, b, and c, and use a hash table to record the first occurrence position of each (cnt[a] - cnt[b], cnt[b] - cnt[c]) value. When we encounter the same value again, it means that the counts of characters a, b, and c in the substring from the last occurrence position to the current position are equal, i.e., the substring is balanced, and we update the answer.

Finally, we calculate the values of calc1(s), calc2(s, 'a', 'b'), calc2(s, 'b', 'c'), calc2(s, 'a', 'c'), and calc3(s) respectively, and return their maximum value.

The time complexity is O(n) and the space complexity is O(n), where n is the length of the string s.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Enumeration (Brute Force)O(n^2)O(1)Small inputs or when first reasoning about the balance condition
Prefix Sum + Hash TableO(n)O(n)General case and interview settings requiring optimal linear-time solution

Video Solution

Longest Balanced Substring II | Detailed | Dry Run | Thought Process | Leetcode 3714 | MIK • codestorywithMIK • 14,721 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Balanced Substring II easy or hard?
Longest Balanced Substring II is typically classified as a medium difficulty problem. The challenge is recognizing the prefix sum pattern that converts the balance condition into a repeated state detection problem.
Longest Balanced Substring II Python/Java solution
Most implementations follow the same structure across languages: compute a running prefix sum, store the first occurrence in a hash map, and update the maximum length when the prefix repeats. The FleetCode solution provides implementations in Python, Java, C++, Go, TypeScript, and Rust.
How to solve Longest Balanced Substring II in O(n)?
Convert the balance condition into a prefix difference. Assign +1 to one character group and -1 to the other, maintain a running sum while scanning the string, and store the earliest index for each prefix value in a hash map. When the same sum reappears, the substring between the two indices is balanced, allowing you to update the maximum length in constant time.
What is the best approach for Longest Balanced Substring II?
The most efficient approach uses prefix sum with a hash table. Map the two character categories to +1 and -1, compute a running prefix sum, and store the first index where each sum appears. When the same prefix value appears again, the substring between those indices is balanced. This gives O(n) time and O(n) space.
Is Longest Balanced Substring II asked at Google/Amazon/Meta?
Balanced substring and prefix-sum hash map patterns frequently appear in interviews at companies like Amazon, Google, and Meta. Variants include equal 0s and 1s, balanced parentheses counts, or equal frequency substring problems.
What data structure is used in Longest Balanced Substring II?
The key data structure is a hash table (hash map) that stores the earliest index of each prefix sum value. Combined with a running prefix sum, it allows constant-time detection of previously seen balance states.
What is the time complexity of Longest Balanced Substring II?
The optimal solution runs in O(n) time using a single pass through the string with constant-time hash map lookups. A brute force enumeration approach exists but requires O(n^2) time because every substring must be checked.

Ready to solve this problem?

Practice Longest Balanced Substring II with our built-in code editor and test cases.

Practice on FleetCode