Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: s = "aababbb" Output: 3 Explanation: All possible variances along with their respective substrings are listed below: - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb". - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab". - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb". - Variance 3 for substring "babbb". Since the largest possible variance is 3, we return it.
Example 2:
Input: s = "abcde" Output: 0 Explanation: No letter occurs more than once in s, so the variance of every substring is 0.
Constraints:
1 <= s.length <= 104s consists of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
"aababbb"
"abcde"
maximum-subarray)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2272: Substring With Largest Variance
class Solution {
public int largestVariance(String s) {
int n = s.length();
int ans = 0;
for (char a = 'a'; a <= 'z'; ++a) {
for (char b = 'a'; b <= 'z'; ++b) {
if (a == b) {
continue;
}
int[] f = new int[] {0, -n};
for (int i = 0; i < n; ++i) {
if (s.charAt(i) == a) {
f[0]++;
f[1]++;
} else if (s.charAt(i) == b) {
f[1] = Math.max(f[0] - 1, f[1] - 1);
f[0] = 0;
}
ans = Math.max(ans, f[1]);
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #2272: Substring With Largest Variance
func largestVariance(s string) int {
ans, n := 0, len(s)
for a := 'a'; a <= 'z'; a++ {
for b := 'a'; b <= 'z'; b++ {
if a == b {
continue
}
f := [2]int{0, -n}
for _, c := range s {
if c == a {
f[0]++
f[1]++
} else if c == b {
f[1] = max(f[1]-1, f[0]-1)
f[0] = 0
}
ans = max(ans, f[1])
}
}
}
return ans
}
# Accepted solution for LeetCode #2272: Substring With Largest Variance
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
// Accepted solution for LeetCode #2272: Substring With Largest Variance
/**
* [2272] Substring With Largest Variance
*
* 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.
*
* Example 1:
*
* Input: s = "aababbb"
* Output: 3
* Explanation:
* All possible variances along with their respective substrings are listed below:
* - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb".
* - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab".
* - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb".
* - Variance 3 for substring "babbb".
* Since the largest possible variance is 3, we return it.
*
* Example 2:
*
* Input: s = "abcde"
* Output: 0
* Explanation:
* No letter occurs more than once in s, so the variance of every substring is 0.
*
*
* Constraints:
*
* 1 <= s.length <= 10^4
* s consists of lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/substring-with-largest-variance/
// discuss: https://leetcode.com/problems/substring-with-largest-variance/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn largest_variance(s: String) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2272_example_1() {
let s = "aababbb".to_string();
let result = 3;
assert_eq!(Solution::largest_variance(s), result);
}
#[test]
#[ignore]
fn test_2272_example_2() {
let s = "abcde".to_string();
let result = 0;
assert_eq!(Solution::largest_variance(s), result);
}
}
// Accepted solution for LeetCode #2272: Substring With Largest Variance
function largestVariance(s: string): number {
const n: number = s.length;
let ans: number = 0;
for (let a = 97; a <= 122; ++a) {
for (let b = 97; b <= 122; ++b) {
if (a === b) {
continue;
}
const f: number[] = [0, -n];
for (let i = 0; i < n; ++i) {
if (s.charCodeAt(i) === a) {
f[0]++;
f[1]++;
} else if (s.charCodeAt(i) === b) {
f[1] = Math.max(f[0] - 1, f[1] - 1);
f[0] = 0;
}
ans = Math.max(ans, f[1]);
}
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.