KatInterview

Max Length Product of Non-Overlapping Disjoint-Alphabet Substrings

StringsAuto-graded · 17 test cases
EasyAuto-gradedStringsstringsmath-bitsarrays

Last 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) <= 100
  • s contains 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.