Find the Divisibility Array of a String - 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.

Return the divisibility array of word.

Input & Output

Example 1 — Basic Case
$ Input: word = "998", m = 7
Output: [0,0,1]
💡 Note: "9" = 9, 9 % 7 = 2 ≠ 0, so div[0] = 0. "99" = 99, 99 % 7 = 1 ≠ 0, so div[1] = 0. "998" = 998, 998 % 7 = 0, so div[2] = 1.
Example 2 — Multiple Divisible Prefixes
$ Input: word = "1010", m = 10
Output: [0,0,1,1]
💡 Note: "1" = 1 % 10 ≠ 0, "10" = 10 % 10 = 0, "101" = 101 % 10 ≠ 0, "1010" = 1010 % 10 = 0.
Example 3 — Single Digit
$ Input: word = "5", m = 5
Output: [1]
💡 Note: "5" = 5, and 5 % 5 = 0, so div[0] = 1.

Constraints

  • 1 ≤ word.length ≤ 105
  • word consists of digits only
  • 1 ≤ m ≤ 109

Visualization

Tap to expand
Divisibility Array: word = "998", m = 7Input String:998Check divisibility by m = 7Prefix "9" → 9 % 7 = 2 ≠ 0Prefix "99" → 99 % 7 = 1 ≠ 0Prefix "998" → 998 % 7 = 0 ✓Output Array:001
Understanding the Visualization
1
Input
String of digits and divisor m
2
Process
Check each prefix for divisibility using modular arithmetic
3
Output
Array where 1 means prefix is divisible by m, 0 otherwise
Key Takeaway
🎯 Key Insight: Use modular arithmetic to track remainder without integer overflow
Asked in
Google 35 Microsoft 28
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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