Number of Divisible Substrings - Problem

Imagine each letter of the alphabet has a secret numerical value: a=1, b=2, c=3, ..., z=26. Now here's the twist - a substring is considered "divisible" if the sum of its character values is perfectly divisible by its length!

For example, in the string "abc":

  • "a" has sum=1, length=1 → 1÷1=1 ✅ (divisible)
  • "ab" has sum=3, length=2 → 3÷2=1.5 ❌ (not divisible)
  • "abc" has sum=6, length=3 → 6÷3=2 ✅ (divisible)

Your mission: count how many substrings in the given string are divisible!

Remember: A substring is any contiguous sequence of characters, and we need to check every possible one.

Input & Output

example_1.py — Basic Case
$ Input: s = "abc"
Output: 4
💡 Note: Character values: a=1, b=2, c=3. Divisible substrings: "a" (sum=1, len=1, 1%1=0), "abc" (sum=6, len=3, 6%3=0), "b" (sum=2, len=1, 2%1=0), "c" (sum=3, len=1, 3%1=0). Total: 4 substrings.
example_2.py — Single Character
$ Input: s = "a"
Output: 1
💡 Note: Only one substring "a" with sum=1, length=1. Since 1%1=0, it's divisible. Result: 1.
example_3.py — No Divisible Substrings
$ Input: s = "bb"
Output: 2
💡 Note: Character values: b=2. Substrings: "b" (sum=2, len=1, 2%1=0) appears twice, "bb" (sum=4, len=2, 4%2=0). All are divisible. Result: 3.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of only lowercase English letters
  • Each character maps to its position in alphabet (a=1, b=2, ..., z=26)

Visualization

Tap to expand
🍕 Pizza Slice Problem VisualizationPizza "abc"a=1b=2c=3Perfect Slices Found:Slice "a": 1÷1 = 1 ✓Slice "ab": 3÷2 = 1.5 ✗Slice "abc": 6÷3 = 2 ✓Slice "b": 2÷1 = 2 ✓Slice "bc": 5÷2 = 2.5 ✗Slice "c": 3÷1 = 3 ✓Total Perfect Slices: 4
Understanding the Visualization
1
Assign Values
Each letter gets a value: a=1 pepperoni, b=2 mushrooms, c=3 olives
2
Check Slices
For each possible slice (substring), calculate total points
3
Test Divisibility
A slice is 'perfect' if total points ÷ number of toppings has no remainder
4
Count Perfect Slices
Sum up all the perfect slices found
Key Takeaway
🎯 Key Insight: Use running sums to avoid recalculating substring values, checking divisibility immediately as we extend each substring.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
23.7K Views
Medium Frequency
~18 min Avg. Time
847 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