Find the Divisibility Array of a String solution and explanation
9 more videos on this problem
Leetcode Weekly contest 334 - Medium - Find the Divisibility Array of a StringPrakhar Agrawal · 7:10 · 803 views
Leetcode 2575: Find the Divisibility Array of a String | Weekly Contest 334Algorithms Casts · 6:43 · 573 views
Find the Divisibility Array of a String | leetcode Weekly 334 | Leetcode MediumBinaryMagic · 13:46 · 559 views
Leetcode 2575 Find the Divisibility Array of a String HindiThinkCode · 9:10 · 521 views
2575. Find the Divisibility Array of a String (Leetcode Medium)Programming Live with Larry · 4:44 · 413 views
Leetcode Weekly Contest 334 | 2575 : Find The Divisibility Array Of A String Solution | In HindiCoding Community | Newton School · 8:16 · 376 views
2575. Find the Divisibility Array of a String - JAVA - Weekly Contest 334 (Detailed explanation)Sourin Majumdar · 8:42 · 216 views
Find the Divisibility Array of a String | Leetcode 2575 | Contest 334Tech Courses · 7:27 · 155 views
2575. Find the Divisibility Array of a String || Hindi || Leetcode Weekly contest 334 26 Feb 2023CodeVed | Sanjib Asiwal · 11:07 · 81 views
Find the Divisibility Array of a String | Leetcode 2575 | Approach + Code with explanation.Pirai's Academy · 8:26 · 31 views
The 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] = 1if the numeric value ofword[0,...,i]is divisible bym, ordiv[i] = 0otherwise.
Return the divisibility array of word.
Example 1:
Input: word = "998244353", m = 3 Output: [1,1,0,0,0,1,1,0,0] Explanation: There are only 4 prefixes that are divisible by 3: "9", "99", "998244", and "9982443".
Example 2:
Input: word = "1010", m = 10 Output: [0,1,0,1] Explanation: There are only 2 prefixes that are divisible by 10: "10", and "1010".
Constraints:
1 <= n <= 105word.length == nwordconsists of digits from0to91 <= m <= 109
Approach overview
Problem Overview: You are given a numeric string word and an integer m. For each prefix of the string, determine whether the number formed by that prefix is divisible by m. The result is a binary array where 1 means the prefix is divisible and 0 means it is not.
Approach 1: Iterative Modulo Calculation (O(n) time, O(1) space)
Construct the number incrementally while iterating through the string. Instead of converting the entire prefix into a large integer, maintain the current remainder using modular arithmetic. For each character, update the remainder with remainder = (remainder * 10 + digit) % m. If the remainder becomes 0, the current prefix is divisible by m, so record 1; otherwise record 0. This avoids large integer overflow and processes each character exactly once.
This approach relies on properties from math and sequential processing of a string. Since only the current remainder is stored, space usage stays constant. This is the optimal solution and scales efficiently even when the string length is up to 10^5.
Approach 2: Prefix Construction with BigInteger (O(n^2) time, O(n) space)
Another method builds each prefix number explicitly using a big integer representation. At every step, append the new digit to the previous value using a BigInteger (in Java) and check divisibility using mod. This works because big integer libraries support arbitrary precision arithmetic.
The drawback is that the prefix value grows with every digit. Each arithmetic operation becomes more expensive as the number length increases, leading to roughly O(n^2) total time in practice. Memory usage also grows because the full prefix number must be stored. This approach is easier to reason about conceptually but inefficient for long inputs.
Recommended for interviews: The iterative modulo approach is the expected solution. It demonstrates understanding of modular arithmetic and efficient prefix processing. Interviewers want to see that you avoid constructing huge integers and instead track the remainder while iterating through the array-like structure of digits. Mentioning the BigInteger approach first can show baseline thinking, but implementing the modulo trick proves strong algorithmic intuition.
Approach 1: Iterative Modulo Calculation
Iterative Modulo Calculation: In this approach, we iterate through the string and maintain a running computation of the numeric value of the prefix modulo m. By keeping track of this value, we can determine if the current prefix is divisible by m without fully computing its numeric value (which could be large). This method efficiently checks divisibility by taking advantage of the mathematical properties of the modulo operation.
def find_divisibility_array(word, m):
result = []
prefix = 0
for char in word:
prefix = (prefix * 10 + int(char)) % m
result.append(1 if prefix == 0 else 0)
return result
word = "998244353"
m = 3
print(find_divisibility_array(word, m))import java.util.*;
public class DivisibilityArray {
public static int[] findDivisibilityArray(String word, int m) {
int[] result = new int[word.length()];
long prefix = 0;
for (int i = 0; i < word.length(); i++) {
prefix = (prefix * 10 + (word.charAt(i) - '0')) % m;
result[i] = (prefix == 0) ? 1 : 0;
}
return result;
}
public static void main(String[] args) {
String word = "998244353";
int[] result = findDivisibilityArray(word, 3);
System.out.println(Arrays.toString(result));
}
}#include <iostream>
#include <vector>
using namespace std;
vector<int> findDivisibilityArray(string word, int m) {
vector<int> result(word.size(), 0);
long long prefix = 0;
for (size_t i = 0; i < word.size(); i++) {
prefix = (prefix * 10 + (word[i] - '0')) % m;
result[i] = (prefix == 0) ? 1 : 0;
}
return result;
}
int main() {
string word = "998244353";
int m = 3;
vector<int> result = findDivisibilityArray(word, m);
for (int r : result) {
cout << r << " ";
}
return 0;
}function findDivisibilityArray(word, m) {
const result = [];
let prefix = 0;
for (let char of word) {
prefix = (prefix * 10 + parseInt(char)) % m;
result.push(prefix === 0 ? 1 : 0);
}
return result;
}
const word = "998244353";
const m = 3;
console.log(findDivisibilityArray(word, m));#include <stdio.h>
#include <string.h>
void findDivisibilityArray(const char *word, int m, int *result) {
long long prefix = 0;
int n = strlen(word);
for (int i = 0; i < n; i++) {
prefix = (prefix * 10 + (word[i] - '0')) % m;
result[i] = (prefix == 0) ? 1 : 0;
}
}
int main() {
char word[] = "998244353";
int m = 3;
int result[strlen(word)];
findDivisibilityArray(word, m, result);
for (int i = 0; i < strlen(word); i++) {
printf("%d ", result[i]);
}
return 0;
}using System;
class DivisibilityArray {
static int[] FindDivisibilityArray(string word, int m) {
int[] result = new int[word.Length];
long prefix = 0;
for (int i = 0; i < word.Length; i++) {
prefix = (prefix * 10 + (word[i] - '0')) % m;
result[i] = prefix == 0 ? 1 : 0;
}
return result;
}
static void Main() {
string word = "998244353";
int m = 3;
int[] result = FindDivisibilityArray(word, m);
Console.WriteLine(string.Join(" ", result));
}
}This Python function calculates the running prefix modulo and tracks which prefixes are divisible by m, appending the result to a list.
Time Complexity: O(n)
Space Complexity: O(n)
Approach 2: Prefix Sum with BigInteger
Prefix Sum with BigInteger: This approach is useful when handling very large numbers that standard integer types cannot accommodate. By using big integer libraries or constructs, we can compute the prefix sum directly by considering each prefix as a whole number and using higher precision arithmetic to handle larger values. In languages where native big integer support is available, we leverage this capability to simplify our implementation.
import java.math.BigInteger;
import java.util.*;
public class DivisibilityArray {
public static int[] findDivisibilityArray(String word, int m) {
int[] result = new int[word.length()];
BigInteger modulus = BigInteger.valueOf(m);
BigInteger prefix = BigInteger.ZERO;
for (int i = 0; i < word.length(); i++) {
prefix = prefix.multiply(BigInteger.TEN).add(BigInteger.valueOf(word.charAt(i) - '0'));
result[i] = prefix.mod(modulus).equals(BigInteger.ZERO) ? 1 : 0;
}
return result;
}
public static void main(String[] args) {
String word = "998244353";
int m = 3;
int[] result = findDivisibilityArray(word, m);
System.out.println(Arrays.toString(result));
}
}This Java solution applies BigInteger for operations to manage very large prefix values. Such robust arithmetic ensures accuracy over potential integer overflow.
Time Complexity: O(n) per arithmetic operation (though potentially slower due to BigInteger)
Space Complexity: O(n)
Approach 3: Traversal + Modulo
We iterate over the string word, using a variable x to record the modulo result of the current prefix with m. If x is 0, then the divisible array value at the current position is 1, otherwise it is 0.
The time complexity is O(n), where n is the length of the string word. The space complexity is O(1).
function divisibilityArray(word: string, m: number): number[] {
const ans: number[] = [];
let x = 0;
for (const c of word) {
x = (x * 10 + Number(c)) % m;
ans.push(x === 0 ? 1 : 0);
}
return ans;
}func divisibilityArray(word string, m int) (ans []int) {
x := 0
for _, c := range word {
x = (x*10 + int(c-'0')) % m
if x == 0 {
ans = append(ans, 1)
} else {
ans = append(ans, 0)
}
}
return ans
}impl Solution {
pub fn divisibility_array(word: String, m: i32) -> Vec<i32> {
let m = m as i64;
let mut x = 0i64;
word.as_bytes()
.iter()
.map(|&c| {
x = (x * 10 + i64::from(c - b'0')) % m;
if x == 0 {
1
} else {
0
}
})
.collect()
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Iterative Modulo Calculation | Time Complexity: O(n) |
| Prefix Sum with BigInteger | Time Complexity: O(n) per arithmetic operation (though potentially slower due to BigInteger) |
| Traversal + Modulo | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Modulo Calculation | O(n) | O(1) | Best for large strings and interview settings; avoids large integer construction |
| Prefix with BigInteger | O(n^2) | O(n) | Useful when demonstrating the direct numeric interpretation of prefixes using arbitrary precision integers |
Frequently asked questions
Is Find the Divisibility Array of a String easy or hard?
Find the Divisibility Array of a String is typically classified as a Medium problem. The challenge lies in recognizing that constructing full prefix numbers is inefficient and that modular arithmetic can track divisibility efficiently in O(n) time.
Find the Divisibility Array of a String Python/Java solution
In Python or Java, iterate through the string and maintain a running remainder variable. Update it with modular arithmetic and append 1 or 0 to the result depending on whether the remainder becomes zero. The same logic works across Python, Java, C++, JavaScript, and C#.
How to solve Find the Divisibility Array of a String in O(n)?
Iterate through the digits of the string and keep a running remainder. At each step compute remainder = (remainder * 10 + currentDigit) % m. If the remainder equals 0, mark the corresponding index in the result array as 1; otherwise mark it as 0. This processes all prefixes in a single pass.
What is the best approach for Find the Divisibility Array of a String?
The best approach is iterative modulo calculation. Maintain the current remainder while scanning the string and update it with (remainder * 10 + digit) % m. This determines whether each prefix is divisible without building large numbers. The algorithm runs in O(n) time and O(1) space.
Is Find the Divisibility Array of a String asked at Google/Amazon/Meta?
Problems involving prefix processing and modular arithmetic frequently appear in interviews at companies like Google, Amazon, and Meta. While this exact problem may vary, the pattern of maintaining rolling remainders over strings or arrays is a common interview concept.
What data structure is used in Find the Divisibility Array of a String?
The problem mainly uses arrays and strings. The result is stored in an array, while the input is processed as a string of digits. The algorithm relies on modular arithmetic rather than complex data structures.
What is the time complexity of Find the Divisibility Array of a String?
The optimal solution runs in O(n) time where n is the length of the string. Each digit is processed once and the remainder is updated using constant-time modular arithmetic. Space complexity is O(1) excluding the output array.
