Leetcode #2575: Find the Divisibility Array of a String
In this guide, we solve Leetcode #2575 Find the Divisibility Array of a String in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed string word of length n consisting of digits, and a positive integer m. The divisibility array div of word is an integer array of length n such that: div[i] = 1 if the numeric value of word[0,...,i] is divisible by m, or div[i] = 0 otherwise.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Math, String
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: word = "998244353", m = 3
Output: [1,1,0,0,0,1,1,0,0]
Explanation: There are only 4 prefixes that are divisible by 3: "9", "99", "998244", and "9982443".
Python Solution
class Solution:
def divisibilityArray(self, word: str, m: int) -> List[int]:
ans = []
x = 0
for c in word:
x = (x * 10 + int(c)) % m
ans.append(1 if x == 0 else 0)
return ans
Complexity
The time complexity is , where is the length of the string word. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.