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 Subsequences in String INPUT text = "abdcdbc" a b d c d b c 0 1 2 3 4 5 6 pattern = "ac" a c pattern[0]='a', pattern[1]='c' Current "ac" subsequences: a-c(3), a-c(6) = 2 pairs Count of 'c' in text = 2 Count of 'a' in text = 1 ALGORITHM STEPS 1 Count existing pairs Scan text, track 'a' count Add count when 'c' found 2 Option A: Add 'a' at start New pairs = count of 'c' = 2 new subsequences 3 Option B: Add 'c' at end New pairs = count of 'a' = 1 new subsequence 4 Choose maximum max(countC, countA) max(2, 1) = 2 Greedy Choice: existing = 2 add_best = max(2, 1) = 2 result = 2 + 2 = 4 FINAL RESULT Best: Add 'a' at beginning a a b d c d b c "aabdcdbc" (added 'a') All "ac" subsequences: 1. a[0] - c[4] (new 'a') 2. a[0] - c[7] (new 'a') 3. a[1] - c[4] (original) 4. a[1] - c[7] (original) Total: 4 subsequences Output: 4 Key Insight: Greedy approach: Adding pattern[0] at the START maximizes pairs if count(pattern[1]) is larger. Adding pattern[1] at the END maximizes pairs if count(pattern[0]) is larger. Choose max! Result = existing_subsequences + max(count_of_pattern[0], count_of_pattern[1]) TutorialsPoint - Maximize Number of Subsequences in a String | Greedy with Prefix Counting
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