MediumNo. 2575

Find the Divisibility Array of a String — LeetCode 2575 Python Solution

Topics
Array, Math, String
Reading time
2 min

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

PythonSolution
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

Time
O(n)where n is the length of the string `word`
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
2125Number of Laser Beams in a BankMedium
0043Multiply StringsMedium
0048Rotate ImageMedium
0066Plus OneEasy
0168Excel Sheet Column TitleEasy
0171Excel Sheet Column NumberEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.