LeetCode 2575: Find the Divisibility Array of a String Solution
Master LeetCode problem 2575 (Find the Divisibility Array of a String), a medium 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.
Problem Explanation
Explanation:
To solve this problem, we iterate through the given string word from left to right, keeping track of the numeric value of the prefixes. At each step, we calculate the numeric value of the current prefix by multiplying the previous numeric value by 10 and adding the current digit. We then check if this numeric value is divisible by m and update the divisibility array accordingly.
- We initialize the result array
divwith all zeros. - We iterate through the string
word, updating the numeric value of the prefix at each step. - If the numeric value is divisible by
m, we update the corresponding index in thedivarray to 1.
Time Complexity: O(n), where n is the length of the input string word.
Space Complexity: O(n), for storing the divisibility array.
Solution Code
public int[] findDivisibilityArray(String word, int m) {
int n = word.length();
int[] div = new int[n];
int num = 0;
for (int i = 0; i < n; i++) {
num = (num * 10 + (word.charAt(i) - '0')) % m;
if (num == 0) {
div[i] = 1;
}
}
return div;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2575 (Find the Divisibility Array of a String)?
This page provides optimized solutions for LeetCode problem 2575 (Find the Divisibility Array of a String) 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 2575 (Find the Divisibility Array of a String)?
The time complexity for LeetCode 2575 (Find the Divisibility Array of a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2575 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2575 in Java, C++, or Python.