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
  • In substring "1", only digit 1 appears once - 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
  • In substring "12223", digit 2 appears 3 times while digits 1 and 3 appear 1 time each - this is invalid

Return the number of unique substrings that satisfy this condition.

Input & Output

Example 1 — Basic Case
$ Input: s = "1123"
Output: 4
💡 Note: Valid substrings are: "1" (appears twice as different substrings but same string), "11" (digit 1 appears 2 times), "2" (digit 2 appears 1 time), "3" (digit 3 appears 1 time). Unique count is 4.
Example 2 — All Same Digits
$ Input: s = "111"
Output: 3
💡 Note: Valid substrings are: "1", "11", "111". All contain only digit 1 with consistent frequency within each substring.
Example 3 — Single Digit
$ Input: s = "5"
Output: 1
💡 Note: Only one substring "5" which trivially has equal frequency (digit 5 appears once).

Constraints

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

Visualization

Tap to expand
INPUTString: "1123"11230123Check all possiblesubstrings for equaldigit frequenciesALGORITHM1Build prefix sums2Check each substring3Validate frequencies4Store unique valid onesExample Check:Substring "11": digit 1 appears 2 timesOnly one digit type → Valid ✓Substring "112": 1 appears 2x, 2 appears 1x → Invalid ❌RESULT4Unique SubstringsValid substrings:"1", "11", "2", "3"Time: O(n²)Space: O(n²)Key Insight:Prefix sums enable O(1) frequency calculation for any substring, reducing time complexity from O(n³) to O(n²)TutorialsPoint - Unique Substrings With Equal Digit Frequency | Prefix Sum Approach
Asked in
Google 12 Amazon 8 Microsoft 6
23.4K 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