Maximize Number of Subsequences in a String - Problem
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters.
You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text.
Return the maximum number of times pattern can occur as a subsequence of the modified text.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Input & Output
Example 1 — Basic Case
$
Input:
text = "abdcdbc", pattern = "ac"
›
Output:
4
💡 Note:
Adding 'a' at the start gives "aabdcdbc". We can form "ac" subsequences: positions (0,4), (0,6), (1,4), (1,6) = 4 total.
Example 2 — Same Characters
$
Input:
text = "aabb", pattern = "ab"
›
Output:
6
💡 Note:
Adding 'a' at start gives "aaabb" with 3 'a's and 2 'b's. Total subsequences = 3 × 2 = 6.
Example 3 — Identical Pattern
$
Input:
text = "aa", pattern = "aa"
›
Output:
3
💡 Note:
Adding another 'a' gives 3 'a's total. Number of ways to choose 2 from 3 = C(3,2) = 3.
Constraints
- 1 ≤ text.length ≤ 105
- pattern.length == 2
- text and pattern consist of lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code