Find the Divisibility Array of a String — LeetCode 2575 Python Solution
- Problem
- #2575
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string `word` |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2575. Find the Divisibility Array of a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2575. Find the Divisibility Array of a String?
- LeetCode 2575. Find the Divisibility Array of a String is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2575. Find the Divisibility Array of a String?
- The Python solution on this page runs in O(n), where n is the length of the string `word`.
- What is the space complexity of LeetCode 2575. Find the Divisibility Array of a String?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2575. Find the Divisibility Array of a String cover?
- LeetCode 2575. Find the Divisibility Array of a String is tagged Array, Math and String on LeetCode.