KatInterview

Maximum Length of Equally Frequent Character Substring

StringsAuto-graded · 26 test cases
EasyAuto-gradedStringssliding-windowhash-mapfrequency-counting

Last updated

Find the longest contiguous substring where all distinct characters appear with identical frequency.

Given a string composed of lowercase English letters, determine the length of the longest contiguous substring where each distinct character that appears in it occurs exactly the same number of times.

A substring qualifies if all characters present have equal frequency. Characters not present in the substring are not considered. For instance, a substring consisting of a single repeated character qualifies because that one character appears uniformly throughout.

Write a function that takes a string and returns the length of the longest qualifying substring.

Parameters

  • s (str): A string of lowercase English letters

Returns

  • (int): The length of the longest substring with uniform character frequencies

Constraints

  • 1 <= len(s) <= 1000
  • s contains only lowercase letters a through z
  • Every single character forms a valid substring, so the result is at least 1

Behavior Notes

  • A substring must be contiguous and non-empty
  • Only characters actually present in the substring need to have matching counts
  • If multiple substrings tie for the longest length, return that length (any tie is acceptable)

Examples

Example 1

Input: max_uniform_freq_substring('aabbc')

Output: 4

Example 2

Input: max_uniform_freq_substring('aaab')

Output: 3

Example 3

Input: max_uniform_freq_substring('xyzzyxx')

Output: 6

Hints

Hint 1

Try checking all possible substrings systematically by fixing the start position and extending the end position one character at a time

Hint 2

Track the frequency of each character incrementally as you extend the window rather than recounting from scratch

Hint 3

A window is valid when the total length equals the maximum frequency multiplied by the number of distinct characters present