Number of Equal Count Substrings - Problem

Imagine you're analyzing text patterns where balance matters. You have a string containing only lowercase English letters, and you need to find all substrings where each unique character appears exactly the same number of times.

Given a string s and an integer count, find all equal count substrings where every unique letter appears exactly count times. For example, in "aaabbb" with count = 3, the entire string is an equal count substring because both 'a' and 'b' appear exactly 3 times.

Goal: Return the total number of such balanced substrings.

Input: A string s and integer count
Output: Number of equal count substrings

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "aaabbbccc", count = 3
โ€บ Output: 3
๐Ÿ’ก Note: Three valid substrings: "aaa" (a appears 3 times), "bbb" (b appears 3 times), and "ccc" (c appears 3 times). Each has exactly one unique character appearing exactly 3 times.
example_2.py โ€” Mixed Characters
$ Input: s = "abab", count = 2
โ€บ Output: 1
๐Ÿ’ก Note: Only one valid substring: "abab" where both 'a' and 'b' appear exactly 2 times each. Shorter substrings don't have the required count.
example_3.py โ€” No Valid Substrings
$ Input: s = "abc", count = 2
โ€บ Output: 0
๐Ÿ’ก Note: No substring can have any character appearing exactly 2 times since each character appears only once in the entire string.

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • 1 โ‰ค count โ‰ค s.length
  • s consists of only lowercase English letters
  • All characters in a valid substring must appear exactly count times

Visualization

Tap to expand
Equal Count Substring Algorithm VisualizationPattern Recognition: Length = Unique Characters ร— Count"aaa"1 ร— 3 = 3"aabb"2 ร— 2 = 4"aaabbb"2 ร— 3 = 6"aabbccdd"4 ร— 2 = 8Sliding Window for k=2, count=3a a a b b b c c c d d daaabbb โœ“bbbccc โœ“cccddd โœ“๐ŸŽฏ Key Insight: Process each unique character count k systematically with sliding window
Understanding the Visualization
1
Identify the Pattern
Valid substrings have predictable lengths: k unique chars ร— count occurrences each
2
Systematic Search
For each k from 1 to 26, use sliding window to find valid windows of length kร—count
3
Window Validation
Check if current window has exactly k unique characters, each appearing exactly count times
4
Efficient Counting
Sliding window eliminates redundant work, achieving O(n) complexity
Key Takeaway
๐ŸŽฏ Key Insight: By recognizing that valid substrings have predictable lengths and using sliding windows for each possible unique character count, we achieve optimal O(n) time complexity instead of the naive O(nยณ) approach.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
28.4K Views
Medium-High Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen