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
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.
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code