LeetCode 3448: Count Substrings Divisible By Last Digit Solution
Master LeetCode problem 3448 (Count Substrings Divisible By Last Digit), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3448. Count Substrings Divisible By Last Digit
Problem Explanation
Explanation:
To solve this problem, we can iterate through all substrings of the given string and check if the substring is divisible by its non-zero last digit. We can optimize this approach by calculating the count of substrings that are divisible by each digit from 1 to 9.
Steps:
- Initialize an array
divisibleCountof size 10 to store the count of substrings divisible by each digit from 0 to 9. - Initialize a variable
resultto store the final count of substrings that are divisible by their non-zero last digit. - Iterate through each digit in the input string
s. - For each digit, iterate through all possible substrings ending at that digit and update the count in the
divisibleCountarray. - Finally, calculate the total count of substrings that are divisible by their non-zero last digit using the values in the
divisibleCountarray.
Time Complexity: O(n), where n is the length of the input string s.
Space Complexity: O(1) as we are using a fixed-size array of size 10.
Solution Code
public int countSubstringsDivisibleByLastDigit(String s) {
int[] divisibleCount = new int[10];
int result = 0;
for (char c : s.toCharArray()) {
int digit = c - '0';
int[] newDivisibleCount = new int[10];
for (int i = 0; i < 10; i++) {
newDivisibleCount[(i * 10 + digit) % 10] += divisibleCount[i];
}
newDivisibleCount[digit % 10]++;
divisibleCount = newDivisibleCount;
result += divisibleCount[0]; // Count of substrings ending in zero
}
return result;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3448 (Count Substrings Divisible By Last Digit)?
This page provides optimized solutions for LeetCode problem 3448 (Count Substrings Divisible By Last Digit) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3448 (Count Substrings Divisible By Last Digit)?
The time complexity for LeetCode 3448 (Count Substrings Divisible By Last Digit) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3448 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3448 in Java, C++, or Python.