#2272

Substring With Largest Variance

Hard
Hash TableStringDynamic ProgrammingEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution focuses on pairs of characters and uses a modified counting approach to efficiently calculate the variance. By treating one character as +1 and another as -1, we can track the maximum variance using a single pass through the string.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through all pairs of distinct characters in the string.
  2. 2Step 2: For each pair, traverse the string, treating one character as +1 and the other as -1.
  3. 3Step 3: Maintain a running total and track the maximum variance encountered, resetting when the total becomes negative.
solution.py21 lines
1# Full working Python code
2
3def largestVariance(s):
4    max_variance = 0
5    unique_chars = set(s)
6    for a in unique_chars:
7        for b in unique_chars:
8            if a != b:
9                count_a = count_b = 0
10                for char in s:
11                    if char == a:
12                        count_a += 1
13                    elif char == b:
14                        count_b += 1
15                    if count_b > count_a:
16                        count_a = count_b = 0
17                    max_variance = max(max_variance, count_a - count_b)
18    return max_variance
19
20# Example usage
21print(largestVariance('aababbb'))  # Output: 3

Complexity note: The time complexity is O(n²) because we iterate through all pairs of distinct characters, and for each pair, we traverse the string once. The space complexity is O(1) since we only use a fixed amount of extra space regardless of input size.

  • 1The variance is maximized by focusing on pairs of characters.
  • 2Resetting counts when one character exceeds another helps track the variance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.