Katkat

Longest Substring in Which Every Present Letter Occurs Equally Often

DRWSoftware Engineer · Technical Screen

Last updated

Given a string of lowercase letters, find the length of the longest substring in which every letter that appears occurs the same number of times. It tests substring enumeration with incremental frequency tracking and a precise definition of what counts as balanced.

A string is balanced if every letter that occurs in it occurs the same number of times. For example, "aabb", "abc" and "zzz" are balanced, while "aab" is not. Given a string of lowercase English letters, return the length of its longest balanced substring.

Function Signature

def longest_balanced_substring(s: str) -> int:

Rules

  • A substring is a contiguous, non-empty part of s.
  • Only the letters that occur in the substring are compared; letters that do not occur in it are ignored. A substring made of one repeated letter is therefore balanced.
  • Every single character is a balanced substring, so the answer is at least 1.

Constraints

  • 1 <= len(s) <= 1000
  • s consists only of lowercase English letters a to z.

Examples

Example 1

Input: s = "aabbc"
Output: 4

"aabb" contains a twice and b twice. The only longer substring is the whole string, in which c occurs once while a and b occur twice.

Example 2

Input: s = "aaab"
Output: 3

The whole string has three a and one b, so it is not balanced. "aaa" contains only a, so it is balanced.

Example 3

Input: s = "xyzzyxx"
Output: 6

Both "xyzzyx" and "yzzyxx" contain each of x, y and z exactly twice. The whole string contains x three times, so it is not balanced.