#3448
Count Substrings Divisible By Last Digit
HardStringDynamic ProgrammingDynamic ProgrammingString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses dynamic programming to keep track of the counts of valid substrings ending at each index, leveraging the properties of modular arithmetic to avoid recalculating values.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a count variable to store the total number of valid substrings.
- 2Step 2: Use a loop to iterate through each character in the string as the end of a substring.
- 3Step 3: For each character, check if it is a non-zero digit and calculate the current number formed by the substring ending at this character.
- 4Step 4: Use modular arithmetic to check if the number is divisible by its last digit and update the count accordingly.
solution.py16 lines
1# Full working Python code
2
3def count_divisible_substrings(s):
4 count = 0
5 n = len(s)
6 for i in range(n):
7 current_number = 0
8 for j in range(i, n):
9 current_number = current_number * 10 + int(s[j])
10 last_digit = int(s[j])
11 if last_digit != 0 and current_number % last_digit == 0:
12 count += 1
13 return count
14
15# Example usage
16print(count_divisible_substrings('12936'))ℹ
Complexity note: The time complexity is O(n) because we only traverse the string once while accumulating the current number. The space complexity is O(1) since we are using a constant amount of extra space.
- 1Substrings that end with a non-zero digit can be checked for divisibility by that digit.
- 2Dynamic programming can help optimize the counting of valid substrings without recalculating values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.