#2575
Find the Divisibility Array of a String
MediumArrayMathStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of recalculating the numeric value for each prefix, we can maintain a running total that updates as we add each digit. This allows us to compute the divisibility in constant time for each new character.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty array div of length n and a variable remainder set to 0.
- 2Step 2: For each index i from 0 to n-1, update the remainder using the formula: remainder = (remainder * 10 + int(word[i])) % m.
- 3Step 3: If remainder is 0, set div[i] to 1, otherwise set it to 0.
solution.py9 lines
1# Full working Python code
2word = '998244353'
3m = 3
4div = []
5remainder = 0
6for i in range(len(word)):
7 remainder = (remainder * 10 + int(word[i])) % m
8 div.append(1 if remainder == 0 else 0)
9print(div)ℹ
Complexity note: This complexity is O(n) because we only make a single pass through the string, updating the remainder in constant time for each character.
- 1Using a running total for the remainder avoids recalculating the entire prefix value each time.
- 2Understanding how to manipulate remainders can simplify many problems involving divisibility.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.