Longest Balanced Substring II

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
Inputs = "abbac"
Output4
The longest balanced substring is "abba" because both distinct characters 'a' and 'b' each appear exactly 2 times.
Example 2
Inputs = "aabcc"
Output3
The longest balanced substring is "abc" because all distinct characters 'a', 'b' and 'c' each appear exactly 1 time.

Constraints

  • 1 <= s.length <= 10^5
  • s contains only the characters 'a', 'b', and 'c'.

Asked at 6 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate