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
Maximize Pattern SubsequencesInput Text"abdab"Pattern"ab"Option 1:Add 'a' at start→ 3 subsequencesOriginal text:No addition→ 2 subsequencesOption 2:Add 'b' at end→ 2 subsequencesMaximum Result: 3 subsequencesBest strategy: Add first character at beginning
Understanding the Visualization
1
Input
Text string and 2-character pattern
2
Process
Add one pattern character optimally
3
Output
Maximum possible subsequence count
Key Takeaway
🎯 Key Insight: Adding pattern[0] at start or pattern[1] at end usually gives optimal results
Asked in
Google 15 Microsoft 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
823 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen