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,1,0,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 of a String INPUT word = "998" 9 i=0 9 i=1 8 i=2 m = 7 Numeric Prefixes: "9" --> 9 "99" --> 99 "998" --> 998 Check each prefix mod 7 for divisibility ALGORITHM STEPS 1 Initialize remainder = 0, div = [] 2 i=0: Process '9' rem = (0*10 + 9) % 7 = 2 2 != 0, div[0] = 0 3 i=1: Process '9' rem = (2*10 + 9) % 7 = 1 1 != 0, div[1] = 0 4 i=2: Process '8' rem = (1*10 + 8) % 7 = 4 18 % 7 = 4... Wait! 998 % 7 = 0, div[2] = 1 Modular Formula: new_rem = (rem*10 + digit) % m Avoids large number overflow FINAL RESULT Divisibility Array: 0 9%7=2 0 99%7=1 1 998%7=0 [0, 0, 1] Verification: 998 / 7 = 142.57... 998 = 7 x 142 + 4 Wait, 7 x 142 = 994 7 x 142 + 4 = 998 OK Correction: Not divisible Key Insight: Use modular arithmetic: (prev_remainder * 10 + current_digit) % m to avoid integer overflow. This works because: (a * b + c) % m = ((a % m) * (b % m) + (c % m)) % m Time: O(n) | Space: O(n) for result array | No need to compute actual large prefix numbers! TutorialsPoint - Find the Divisibility Array of a String | Optimal Solution
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