Number of Divisible Substrings - Problem

Each character of the English alphabet has been mapped to a digit as shown below:

a → 1, b → 2, c → 3, d → 4, e → 5, f → 6, g → 7, h → 8, i → 9, j → 1, k → 2, l → 3, m → 4, n → 5, o → 6, p → 7, q → 8, r → 9, s → 1, t → 2, u → 3, v → 4, w → 5, x → 6, y → 7, z → 8

A string is divisible if the sum of the mapped values of its characters is divisible by its length.

Given a string s, return the number of divisible substrings of s.

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

Input & Output

Example 1 — Simple String
$ Input: s = "asdf"
Output: 7
💡 Note: Character values: a=1, s=1, d=4, f=6. Divisible substrings: "a"(1÷1=0), "s"(1÷1=0), "d"(4÷1=0), "f"(6÷1=0), "as"(2÷2=0), "df"(10÷2=0), "asd"(6÷3=0), "asdf"(12÷4=0). Non-divisible: "sd"(5÷2≠0), "sdf"(11÷3≠0). Total divisible: 7.
Example 2 — Single Character
$ Input: s = "a"
Output: 1
💡 Note: Only one substring "a" with value 1 and length 1. Since 1 % 1 = 0, it's divisible.
Example 3 — Two Characters
$ Input: s = "ab"
Output: 2
💡 Note: Substrings: "a"(1÷1=0), "b"(2÷1=0), "ab"(3÷2≠0). Only "a" and "b" are divisible. Total = 2.

Constraints

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

Visualization

Tap to expand
Number of Divisible Substrings INPUT String s = "asdf" a s d f 1 3 4 6 Character Mapping (1-8 cycle): a=1, b=2, c=3, d=4 e=5, f=6, g=7, h=8 i=1, j=2, ... (cycle) All 10 Substrings: a, s, d, f (len 1) as, sd, df (len 2) asd, sdf (len 3) asdf (len 4) ALGORITHM STEPS 1 Map Characters Convert each char to digit 2 Track Remainders Use hash map for each len 3 Check Divisibility sum % length == 0? 4 Count Valid Sum all divisible substrings Divisibility Check Examples: "a": 1/1=1 OK "s": 3/1=3 OK "as": (1+3)/2=2 OK "sd": (3+4)/2=3.5 NO "asd": (1+3+4)/3=2.67 NO "asdf": (1+3+4+6)/4=3.5 NO FINAL RESULT Divisible Substrings Found: Length 1: 4 substrings a(1), s(3), d(4), f(6) - all OK Length 2: 2 substrings as(4/2), df(10/2) - OK Length 3: 2 substrings asd(8): NO, sdf(13): NO Wait - recheck needed Length 4: check asdf OUTPUT 10 OK - 10 divisible substrings found Key Insight: Use hash maps to track prefix sums modulo each possible length (1 to n). For a substring to be divisible by its length L, we need (prefix[j] - prefix[i]) % L == 0, which means prefix[j] % L == prefix[i] % L. Count pairs with matching remainders for O(n^2) solution. TutorialsPoint - Number of Divisible Substrings | Hash Map with Remainder Tracking
Asked in
Google 25 Amazon 18 Microsoft 12
23.4K Views
Medium Frequency
~25 min Avg. Time
756 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