Problem Description
Given a 0-indexed string word composed of digits and a positive integer m, you need to return an array div where for each index i, div[i] is 1 if the numeric value of the prefix word[0...i] is divisible by m, otherwise 0.
Key Insights
- Rather than converting large prefixes to integers (which can be computationally expensive), use modular arithmetic.
- Compute the rolling modulus: for each digit, update mod = (mod * 10 + current_digit) % m.
- Check if mod is zero after each update to determine divisibility.
- The algorithm processes each digit in a single pass, making it efficient for long strings.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(n), for the output array that stores the divisibility flags.
Solution
We use a rolling modulus technique to check divisibility of each prefix without converting the entire prefix to an integer. By initializing a variable mod as 0, we update it for every digit using the relation mod = (mod * 10 + digit) % m. If at any step mod equals 0, the prefix is divisible by m and we mark that index with 1 in our result array. This approach avoids handling very large numbers and operates in a single pass through the string.