Find the Divisibility Array of a String - Problem
You are given a string word consisting of digits and a positive integer m. Your task is to create a divisibility array that tells you whether each prefix of the string is divisible by m.

For each position i in the string, you need to check if the number formed by characters from index 0 to i is divisible by m. If it is, set div[i] = 1, otherwise set div[i] = 0.

Example: If word = "998244353" and m = 3, then:
• Prefix "9" → 9 % 3 = 0 → div[0] = 1
• Prefix "99" → 99 % 3 = 0 → div[1] = 1
• Prefix "998" → 998 % 3 = 2 → div[2] = 0

The challenge is handling very large numbers that can't fit in standard integer types!

Input & Output

example_1.py — Basic Case
$ Input: word = "998244353", m = 3
Output: [1, 1, 0, 0, 0, 1, 1, 0, 0]
💡 Note: Checking each prefix: "9"(9%3=0✓), "99"(99%3=0✓), "998"(998%3=2✗), "9982"(9982%3=1✗), "99824"(99824%3=1✗), "998244"(998244%3=0✓), "9982443"(9982443%3=0✓), "99824435"(99824435%3=1✗), "998244353"(998244353%3=2✗)
example_2.py — All Divisible
$ Input: word = "1010", m = 10
Output: [0, 1, 0, 1]
💡 Note: Prefixes: "1"(1%10=1✗), "10"(10%10=0✓), "101"(101%10=1✗), "1010"(1010%10=0✓)
example_3.py — Single Digit
$ Input: word = "5", m = 5
Output: [1]
💡 Note: Only one prefix "5", and 5%5=0, so result is [1]

Constraints

  • 1 ≤ word.length ≤ 105
  • word consists of digits only
  • 1 ≤ m ≤ 109
  • Important: The number represented by word can be extremely large and may not fit in standard integer types

Visualization

Tap to expand
Modular Arithmetic FlowStartrem = 0ProcessDigitrem = (rem*10+d)%mCheckrem==0?YESdiv[i] = 1NOdiv[i] = 0Next digitExample: word="123", m=4Step 1: digit=1, rem=(0*10+1)%4=1 → div[0]=0Step 2: digit=2, rem=(1*10+2)%4=0 → div[1]=1Step 3: digit=3, rem=(0*10+3)%4=3 → div[2]=0Result: [0,1,0] ✓
Understanding the Visualization
1
Start Fresh
Begin with remainder = 0, like resetting our special calculator
2
Add New Digit
For each digit, calculate: remainder = (remainder * 10 + digit) % m
3
Check Division
If remainder equals 0, the current prefix is perfectly divisible
4
Continue Rolling
The remainder carries forward, maintaining our running calculation
Key Takeaway
🎯 Key Insight: By maintaining only the remainder instead of the full number, we can handle arbitrarily large inputs while keeping constant space and linear time complexity!
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.5K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen