Number of Equal Count Substrings - Problem

You are given a 0-indexed string s consisting of only lowercase English letters, and an integer count.

A substring of s is said to be an equal count substring if, for each unique letter in the substring, it appears exactly count times in the substring.

Return the number of equal count substrings in s.

A substring is a contiguous non-empty sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "aaabbbccc", count = 3
Output: 3
💡 Note: The equal count substrings are "aaa", "bbb", and "ccc". Each contains one unique character that appears exactly 3 times.
Example 2 — Mixed Characters
$ Input: s = "abababab", count = 2
Output: 3
💡 Note: The equal count substrings are "abab" (positions 0-3), "abab" (positions 2-5), and "abab" (positions 4-7). Each contains 'a' twice and 'b' twice.
Example 3 — No Valid Substrings
$ Input: s = "abcdef", count = 2
Output: 0
💡 Note: No substring has any character appearing exactly 2 times, so there are 0 equal count substrings.

Constraints

  • 1 ≤ s.length ≤ 1000
  • 1 ≤ count ≤ s.length
  • s consists of only lowercase English letters

Visualization

Tap to expand
Number of Equal Count Substrings INPUT String s = "aaabbbccc" a a a b b b c c c 0 1 2 3 4 5 6 7 8 Input Values s = "aaabbbccc" count = 3 Unique Characters 'a', 'b', 'c' (3 unique) Length = 9 Check Window Sizes k=1: len=3, k=2: len=6 k=3: len=9 ALGORITHM STEPS 1 For each k (1 to 26) Window size = k * count 2 Slide window Track char frequencies 3 Count valid chars Chars with freq = count 4 Check if valid valid chars == k Valid Substrings Found: "aaa" k=1, a:3 "bbb" k=1, b:3 "ccc" k=1, c:3 Each has 1 unique char FINAL RESULT Output 3 Explanation Found 3 equal count substrings where each unique char appears 3x Valid Substrings 1. "aaa" [0-2] OK 2. "bbb" [3-5] OK 3. "ccc" [6-8] OK Total count: 3 Key Insight: For k unique characters each appearing 'count' times, window size = k * count. Sliding window with frequency tracking: O(26 * n) time complexity. Only check valid window sizes. TutorialsPoint - Number of Equal Count Substrings | Optimal Solution
Asked in
Google 25 Microsoft 20 Amazon 15 Facebook 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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