Substring With Largest Variance — LeetCode 2272 Python Solution

HardArrayDynamic Programming
Problem
#2272
Reading time
3 min

The problem

The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.

Example

Input
s = "aababbb"
Output
3
Explanation
All possible variances along with their respective substrings are listed below:

Python solution

Python
class Solution:
    def largestVariance(self, s: str) -> int:
        ans = 0
        for a, b in permutations(ascii_lowercase, 2):
            if a == b:
                continue
            f = [0, -inf]
            for c in s:
                if c == a:
                    f[0], f[1] = f[0] + 1, f[1] + 1
                elif c == b:
                    f[1] = max(f[1] - 1, f[0] - 1)
                    f[0] = 0
                if ans < f[1]:
                    ans = f[1]
        return ans

Complexity

MeasureComplexity
TimeO(n \times |\Sigma|^2), where n is the length of the string, and |\Sigma| is the size of the character set
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2272. Substring With Largest Variance is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2272. Substring With Largest Variance?
LeetCode 2272. Substring With Largest Variance is rated Hard on LeetCode.
What is the time complexity of LeetCode 2272. Substring With Largest Variance?
The Python solution on this page runs in O(n \times |\Sigma|^2), where n is the length of the string, and |\Sigma| is the size of the character set.
What is the space complexity of LeetCode 2272. Substring With Largest Variance?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2272. Substring With Largest Variance cover?
LeetCode 2272. Substring With Largest Variance is tagged Array and Dynamic Programming 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.

Get Stealth Interview