Count Substrings Divisible By Last Digit - Problem

You are given a string s consisting of digits. Return the number of substrings of s divisible by their non-zero last digit.

Note: A substring may contain leading zeros.

Input & Output

Example 1 — Basic Case
$ Input: s = "123"
Output: 5
💡 Note: Valid substrings: "1" (1÷1=0), "2" (2÷2=0), "3" (3÷3=0), "12" (12÷2=0), "123" (123÷3=0). Total: 5.
Example 2 — With Zeros
$ Input: s = "1020"
Output: 3
💡 Note: Valid substrings: "1" (1÷1=0), "2" (2÷2=0), "102" (102÷2=0). Substrings ending in 0 are skipped.
Example 3 — Single Digit
$ Input: s = "5"
Output: 1
💡 Note: Only one substring "5", and 5÷5=0, so count is 1.

Constraints

  • 1 ≤ s.length ≤ 103
  • s consists of digits only

Visualization

Tap to expand
Count Substrings Divisible By Last Digit INPUT String s = "123" 1 idx 0 2 idx 1 3 idx 2 All Substrings: "1" "2" "3" "12" "23" "123" Total: 6 substrings Check divisibility by last digit of each ALGORITHM STEPS 1 Track Prefix Sums Store prefix mod values for each divisor 1-9 2 For Each Position Get last digit d as divisor Skip if d = 0 3 Check Divisibility prefix[i] mod d == 0 means divisible 4 Count Valid Pairs Use modular counting to find matching prefixes Divisibility Check: "1" mod 1=0 --> OK "2" mod 2=0 --> OK "3" mod 3=0 --> OK "12" mod 2=0 --> OK "23" mod 3=2 --> NO "123" mod 3=0 --> OK FINAL RESULT Valid Substrings: "1" 1/1=1 OK "2" 2/2=1 OK "3" 3/3=1 OK "12" 12/2=6 OK "123" 123/3=41 OK "23" 23%3=2 NO OUTPUT 5 valid substrings Key Insight: Modular Arithmetic Optimization Instead of checking every substring naively O(n^2), use prefix sums with modular arithmetic. For divisor d, track count of prefixes with each remainder mod d. A substring from i to j is divisible by d if (prefix[j] - prefix[i-1]) mod d == 0, i.e., both have same remainder mod d. TutorialsPoint - Count Substrings Divisible By Last Digit | Modular Arithmetic Optimization
Asked in
Google 25 Microsoft 18 Amazon 15
32.0K Views
Medium Frequency
~25 min Avg. Time
850 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