MediumNo. 2207

Maximize Number of Subsequences in a String — LeetCode 2207 Python Solution

Pattern
Prefix Sum
Topics
Greedy, String, Prefix Sum
Reading time
2 min

The 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.

Example

Input
text = "abdcdbc", pattern = "ac"
Output
4
Explanation
If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4.

Python solution

PythonSolution
class Solution:
    def maximumSubsequenceCount(self, text: str, pattern: str) -> int:
        ans = x = y = 0
        for c in text:
            if c == pattern[1]:
                y += 1
                ans += x
            if c == pattern[0]:
                x += 1
        ans += max(x, y)
        return ans

Complexity

Time
O(n)where n is the length of the string text
Space · auxiliary
O(1)

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2207. Maximize Number of Subsequences in a String is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0316Remove Duplicate LettersMedium
0402Remove K DigitsMedium
0420Strong Password CheckerHard
0649Dota2 SenateMedium
0680Valid Palindrome IIEasy

Frequently asked questions

How hard is LeetCode 2207. Maximize Number of Subsequences in a String?

LeetCode 2207. Maximize Number of Subsequences in a String is rated Medium on LeetCode.

What is the time complexity of LeetCode 2207. Maximize Number of Subsequences in a String?

The Python solution on this page runs in O(n), where n is the length of the string \textit{text}.

What is the space complexity of LeetCode 2207. Maximize Number of Subsequences in a String?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2207. Maximize Number of Subsequences in a String cover?

LeetCode 2207. Maximize Number of Subsequences in a String is tagged Greedy, String and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.