Unique Substrings With Equal Digit Frequency - Problem

You are given a string s that consists only of digits (0-9). Your task is to find the number of unique substrings where every digit that appears in the substring appears the same number of times.

Examples of valid substrings:

  • In substring "112233", digits 1, 2, and 3 each appear exactly 2 times - this is valid
  • In substring "111", only digit 1 appears and it appears 3 times - this is valid

Examples of invalid substrings:

  • In substring "1123", digit 1 appears 2 times while digits 2 and 3 appear 1 time each - this is invalid

Note: The function should return the count of unique substrings that satisfy this condition.

Input & Output

Example 1 — Basic Case
$ Input: s = "1122"
Output: 5
💡 Note: Valid substrings: "1" (appears twice), "2" (appears twice), "11" (digit 1 appears 2 times), "22" (digit 2 appears 2 times), "1122" (both digits appear 2 times each)
Example 2 — Single Digit
$ Input: s = "111"
Output: 3
💡 Note: Valid substrings: "1" (appears 3 times as individual substrings), "11" (appears twice), "111" (digit 1 appears 3 times)
Example 3 — Mixed Frequencies
$ Input: s = "1123"
Output: 6
💡 Note: Valid substrings: "1" (appears twice individually), "2", "3", "11" (digit 1 appears 2 times), "23" (both digits appear 1 time each)

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of digits (0-9)

Visualization

Tap to expand
Unique Substrings With Equal Digit FrequencyInput: s = "1122"1122Valid Substrings (Equal Frequency):"1""2""11""22""1122"1: 1 time2: 1 time1: 2 times2: 2 times1: 2, 2: 2Invalid: "112"1 appears 2 times, 2 appears 1 timeOutput: 5 unique valid substrings
Understanding the Visualization
1
Input Analysis
Given string with digits, identify all possible substrings
2
Frequency Check
For each substring, verify all present digits have same count
3
Count Unique
Return number of unique valid substrings
Key Takeaway
🎯 Key Insight: Use prefix sums to calculate digit frequencies efficiently, then validate equal frequency constraint
Asked in
Google 25 Amazon 18 Facebook 12
23.5K Views
Medium 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