Leetcode 2575: Find the Divisibility Array of a String

grid47
grid47
Exploring patterns and algorithms
Feb 23, 2024 5 min read

Given a string word consisting of digits and an integer m, return an array where each element is 1 if the numeric value of the prefix word[0,…,i] is divisible by m, otherwise 0.
Problem
Approach
Steps
Complexity
Input: The input consists of a string word and an integer m.
Example: For example, word = '2020', m = 4.
Constraints:
• 1 <= n <= 10^5
• word consists of digits from 0 to 9
• 1 <= m <= 10^9
Output: The output is an array of 0s and 1s where each element denotes whether the corresponding prefix of word is divisible by m.
Example: For word = '123456789' and m = 7, the output is [0, 0, 0, 0, 0, 0, 0, 1, 0].
Constraints:
• The length of the divisibility array is the same as the length of word.
Goal: To determine if each prefix of the string word is divisible by m.
Steps:
• 1. Initialize a variable num to store the current numeric value of the prefix.
• 2. For each digit in word, update num by multiplying the previous value by 10 and adding the current digit.
• 3. Check if num is divisible by m, if yes, set div[i] = 1, otherwise div[i] = 0.
Goal: The input string contains digits, and m is a positive integer within the specified range.
Steps:
• 1 <= n <= 10^5
• 1 <= m <= 10^9
• word consists of digits from 0 to 9.
Assumptions:
• The word string is non-empty and consists of digits from '0' to '9'.
Input: For word = '2020' and m = 4, the output is [0, 1, 0, 1].
Explanation: The prefixes '20' and '2020' are divisible by 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus