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: 1
💡 Note: The substring "a" has a=1 occurrences while b=0 occurrences, giving variance 1-0=1. Similarly for other single character substrings with respect to any other character.
Example 3 — Two Characters
$ Input: s = "aab"
Output: 2
💡 Note: The substring "aa" has a=2 occurrences while b=0 occurrences, giving variance 2-0=2. This is the maximum variance possible.

Constraints

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

Visualization

Tap to expand
Substring With Largest Variance INPUT String s = "aababbb" a a b a b b b 0 1 2 3 4 5 6 Character Counts: 'a': 3 'b': 4 Variance = max diff between any 2 char occurrences Best substring: "bababbb" b=4, a=1 --> variance=3 ALGORITHM STEPS 1 Pick char pairs (a,b) Try all 26x26 combinations 2 Kadane's Algorithm Treat 'a' as +1, 'b' as -1 3 Track max diff Reset when sum < 0 4 Ensure both chars exist Min char must appear once Example: a=major, b=minor char: a a b a b b b val: +1 +1 -1 +1 -1 -1 -1 sum: 1 2 1 2 1 0 -1 Max when b is minor = 2 Swap: b major, a minor = 3 FINAL RESULT 3 Largest Variance = 3 Optimal Substring "bababbb" or "ababbb" b:4 - a:1 = 3 Verification: OK Pairs Checked: (a,b): max=3 (b,a): max=3 Global maximum = 3 Time: O(26*26*n) = O(n) Key Insight: Use modified Kadane's algorithm: for each character pair, treat one as +1 and other as -1. Track maximum subarray sum while ensuring the minor character appears at least once. This converts the variance problem into a maximum subarray problem solvable in O(n) per pair. TutorialsPoint - Substring With Largest Variance | Optimal Solution (Modified Kadane's)
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