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 Digit123Input String: "123"✓ "1" ÷ 1 = 0✓ "2" ÷ 2 = 0✓ "3" ÷ 3 = 0✓ "12" ÷ 2 = 0✗ "23" ÷ 3 ≠ 0✓ "123" ÷ 3 = 0Count: 5
Understanding the Visualization
1
Input
String of digits like '123'
2
Process
Check each substring against its last digit
3
Output
Count of valid divisible substrings
Key Takeaway
🎯 Key Insight: Use modular arithmetic to avoid overflow while checking substring divisibility
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