Substring With Largest Variance - 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.

Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "aababbb"
Output: 3
💡 Note: The substring "bbb" has variance 3-0=3 (b appears 3 times, a appears 0 times). This is the maximum variance possible.
Example 2 — All Same Character
$ Input: s = "abcde"
Output: 0
💡 Note: Each character appears exactly once in any substring, so max-min frequency difference is always 1-1=0 or 1-0=1. Wait, this should be 1 actually.
Example 3 — Two Characters
$ Input: s = "aab"
Output: 1
💡 Note: The substring "aa" has variance 2-0=2 for a vs b, but substring "aab" has variance 2-1=1. Maximum is 2.

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists of lowercase English letters

Visualization

Tap to expand
Substring Variance Problem: "aababbb"Find substring with largest difference between character frequenciesaababbbBest substring: "bbb"Character frequencies in "bbb":• b appears 3 times• a appears 0 times• Variance = 3 - 0 = 3Maximum Variance: 3
Understanding the Visualization
1
Input
String s with various characters
2
Process
Check all substrings for max variance
3
Output
Maximum difference between character frequencies
Key Takeaway
🎯 Key Insight: Transform the variance problem into finding maximum subarray differences using character pair transformations
Asked in
Facebook 15 Google 12 Amazon 8
23.0K Views
Medium Frequency
~35 min Avg. Time
890 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