Max Length Product of Non-Overlapping Disjoint-Alphabet Substrings
StringsAuto-graded · 17 test casesLast updated
Find the maximum product of lengths of two non-overlapping substrings that do not share any characters.
Given a string s consisting of lowercase English letters, select two non-overlapping contiguous substrings from s such that they do not share any common characters. Return the maximum possible product of their lengths.
Two substrings s[i..j] and s[k..m] are non-overlapping if j < k (the first ends before the second starts) or m < i (the second ends before the first starts).
If no such pair of non-overlapping substrings exists, return 0.
Constraints
2 <= len(s) <= 100scontains only lowercase English letters ('a'through'z').
Examples
Example 1
Input: max_product_disjoint_substrings('abcde')
Output: 6
Example 2
Input: max_product_disjoint_substrings('aaaaa')
Output: 0
Hints
Hint 1
With the string length up to 100, checking all possible substring pairs is feasible.
Hint 2
Represent the character set of each substring using a 26-bit integer bitmask to make set intersection checks extremely fast.
Hint 3
Notice that non-overlapping means one substring comes entirely before the other.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We need to find two non-overlapping contiguous substrings of s such that they share zero characters, maximizing the product of their lengths.
Since the constraint on the length of s is small ($N \le 100$), we can iterate over all valid pairs of non-overlapping substrings:
- Fix the first substring starting at index
iand ending at indexj(0 <= i <= j < n). - Fix the second substring starting at index
kand ending at indexmsuch thatj < k <= m < n. - Track the set of characters present in each substring. Using a bitmask (where bit $p$ is set if character
chr(ord('a') + p)is present) allows us to check disjointness in $O(1)$ time via bitwise AND (left_mask & right_mask == 0).
Correctness
By requiring j < k, we guarantee that the two substrings do not overlap. By evaluating all valid pairs $(i, j)$ and $(k, m)$, we cover every possible pair of non-overlapping substrings. The bitmask bitwise AND ensures no characters are shared. Thus, taking the maximum product found yields the optimal result.
Complexity
- Time Complexity: $O(N^3)$ or $O(N^4)$ brute force over substring endpoints. Given $N \le 100$, $N^3 \approx 10^6$ operations, which easily runs within the time limit.
- Space Complexity: $O(N)$ auxiliary space to store precalculated bitmasks for individual characters.