Count Substrings Divisible By Last Digit - Problem

You are given a string s consisting only of digits. Your task is to find the number of substrings where each substring is divisible by its last (rightmost) digit.

Key Points:

  • Only consider substrings whose last digit is non-zero (since division by 0 is undefined)
  • A substring can have leading zeros - this is allowed
  • For example, in "123", the substring "12" should be checked if 12 is divisible by 2 (its last digit)

Example: Given s = "1248", the substring "124" ends with digit 4, so we check if 124 is divisible by 4. Since 124 Ć· 4 = 31 with no remainder, this substring counts toward our answer.

Input & Output

example_1.py — Basic Case
$ Input: s = "1248"
› Output: 7
šŸ’” Note: Valid substrings: "1" (1Ć·1=1), "12" (12Ć·2=6), "124" (124Ć·4=31), "1248" (1248Ć·8=156), "2" (2Ć·2=1), "24" (24Ć·4=6), "248" (248Ć·8=31)
example_2.py — With Zeros
$ Input: s = "1230"
› Output: 3
šŸ’” Note: Valid substrings: "1" (1Ć·1=1), "12" (12Ć·2=6), "123" (123Ć·3=41). Substrings ending with '0' are not considered since division by 0 is undefined.
example_3.py — Single Digit
$ Input: s = "5"
› Output: 1
šŸ’” Note: Only one substring "5", and 5Ć·5=1, so it's valid.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of digits (0-9)
  • No leading zeros constraint - substrings may have leading zeros

Visualization

Tap to expand
Count Substrings Divisible By Last DigitExample: s = "1248"1248Valid Substrings:"1"→ 1Ć·1 = 1 āœ“"12"→ 12Ć·2 = 6 āœ“"124"→ 124Ć·4 = 31 āœ“"1248"→ 1248Ć·8 = 156 āœ“+ 3 more substrings: "2", "24", "248"Total: 7 valid substrings
Understanding the Visualization
1
Identify Valid Endings
Find positions with non-zero digits (these can be last digits)
2
Build Substrings
For each valid ending, build all possible substrings ending there
3
Check Divisibility
Use modular arithmetic to check if substring value is divisible by last digit
4
Count Valid Cases
Accumulate the count of all valid substrings
Key Takeaway
šŸŽÆ Key Insight: Use modular arithmetic to check divisibility efficiently without converting entire substrings to integers, avoiding overflow and improving performance.
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22
38.0K Views
Medium-High Frequency
~25 min Avg. Time
1.5K 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