You are given a string s and an integer k. Your task is to find the maximum difference between the frequency of two characters, freq[a] - freq[b], in a substringsubs of s, such that:
subs has a size of at leastk.
Character a has an odd frequency in subs.
Character b has a non-zeroeven frequency in subs.
Return the maximum difference.
Note that subs can contain more than 2 distinct characters.
Example 1:
Input:s = "12233", k = 4
Output:-1
Explanation:
For the substring "12233", the frequency of '1' is 1 and the frequency of '3' is 2. The difference is 1 - 2 = -1.
Example 2:
Input:s = "1122211", k = 3
Output:1
Explanation:
For the substring "11222", the frequency of '2' is 3 and the frequency of '1' is 2. The difference is 3 - 2 = 1.
Example 3:
Input:s = "110", k = 3
Output:-1
Constraints:
3 <= s.length <= 3 * 104
s consists only of digits '0' to '4'.
The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.
Problem summary: You are given a string s and an integer k. Your task is to find the maximum difference between the frequency of two characters, freq[a] - freq[b], in a substring subs of s, such that: subs has a size of at least k. Character a has an odd frequency in subs. Character b has a non-zero even frequency in subs. Return the maximum difference. Note that subs can contain more than 2 distinct characters.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Sliding Window
Example 1
"12233"
4
Example 2
"1122211"
3
Example 3
"110"
3
Related Problems
Frequency of the Most Frequent Element (frequency-of-the-most-frequent-element)
Count Elements With Maximum Frequency (count-elements-with-maximum-frequency)
Step 02
Core Insight
What unlocks the optimal approach
Fix the two characters.
Use prefix sum (maintain 2 characters' parities as status).
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3445: Maximum Difference Between Even and Odd Frequency II
class Solution {
public int maxDifference(String S, int k) {
char[] s = S.toCharArray();
int n = s.length;
final int inf = Integer.MAX_VALUE / 2;
int ans = -inf;
for (int a = 0; a < 5; ++a) {
for (int b = 0; b < 5; ++b) {
if (a == b) {
continue;
}
int curA = 0, curB = 0;
int preA = 0, preB = 0;
int[][] t = {{inf, inf}, {inf, inf}};
for (int l = -1, r = 0; r < n; ++r) {
curA += s[r] == '0' + a ? 1 : 0;
curB += s[r] == '0' + b ? 1 : 0;
while (r - l >= k && curB - preB >= 2) {
t[preA & 1][preB & 1] = Math.min(t[preA & 1][preB & 1], preA - preB);
++l;
preA += s[l] == '0' + a ? 1 : 0;
preB += s[l] == '0' + b ? 1 : 0;
}
ans = Math.max(ans, curA - curB - t[curA & 1 ^ 1][curB & 1]);
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #3445: Maximum Difference Between Even and Odd Frequency II
func maxDifference(s string, k int) int {
n := len(s)
inf := math.MaxInt32 / 2
ans := -inf
for a := 0; a < 5; a++ {
for b := 0; b < 5; b++ {
if a == b {
continue
}
curA, curB := 0, 0
preA, preB := 0, 0
t := [2][2]int{{inf, inf}, {inf, inf}}
l := -1
for r := 0; r < n; r++ {
if s[r] == byte('0'+a) {
curA++
}
if s[r] == byte('0'+b) {
curB++
}
for r-l >= k && curB-preB >= 2 {
t[preA&1][preB&1] = min(t[preA&1][preB&1], preA-preB)
l++
if s[l] == byte('0'+a) {
preA++
}
if s[l] == byte('0'+b) {
preB++
}
}
ans = max(ans, curA-curB-t[curA&1^1][curB&1])
}
}
}
return ans
}
# Accepted solution for LeetCode #3445: Maximum Difference Between Even and Odd Frequency II
class Solution:
def maxDifference(self, S: str, k: int) -> int:
s = list(map(int, S))
ans = -inf
for a in range(5):
for b in range(5):
if a == b:
continue
curA = curB = 0
preA = preB = 0
t = [[inf, inf], [inf, inf]]
l = -1
for r, x in enumerate(s):
curA += x == a
curB += x == b
while r - l >= k and curB - preB >= 2:
t[preA & 1][preB & 1] = min(t[preA & 1][preB & 1], preA - preB)
l += 1
preA += s[l] == a
preB += s[l] == b
ans = max(ans, curA - curB - t[curA & 1 ^ 1][curB & 1])
return ans
// Accepted solution for LeetCode #3445: Maximum Difference Between Even and Odd Frequency II
use std::cmp::{max, min};
use std::i32::{MAX, MIN};
impl Solution {
pub fn max_difference(S: String, k: i32) -> i32 {
let s: Vec<usize> = S
.chars()
.map(|c| c.to_digit(10).unwrap() as usize)
.collect();
let k = k as usize;
let mut ans = MIN;
for a in 0..5 {
for b in 0..5 {
if a == b {
continue;
}
let mut curA = 0;
let mut curB = 0;
let mut preA = 0;
let mut preB = 0;
let mut t = [[MAX; 2]; 2];
let mut l: isize = -1;
for (r, &x) in s.iter().enumerate() {
curA += (x == a) as i32;
curB += (x == b) as i32;
while (r as isize - l) as usize >= k && curB - preB >= 2 {
let i = (preA & 1) as usize;
let j = (preB & 1) as usize;
t[i][j] = min(t[i][j], preA - preB);
l += 1;
if l >= 0 {
preA += (s[l as usize] == a) as i32;
preB += (s[l as usize] == b) as i32;
}
}
let i = (curA & 1 ^ 1) as usize;
let j = (curB & 1) as usize;
if t[i][j] != MAX {
ans = max(ans, curA - curB - t[i][j]);
}
}
}
}
ans
}
}
// Accepted solution for LeetCode #3445: Maximum Difference Between Even and Odd Frequency II
function maxDifference(S: string, k: number): number {
const s = S.split('').map(Number);
let ans = -Infinity;
for (let a = 0; a < 5; a++) {
for (let b = 0; b < 5; b++) {
if (a === b) {
continue;
}
let [curA, curB, preA, preB] = [0, 0, 0, 0];
const t: number[][] = [
[Infinity, Infinity],
[Infinity, Infinity],
];
let l = -1;
for (let r = 0; r < s.length; r++) {
const x = s[r];
curA += x === a ? 1 : 0;
curB += x === b ? 1 : 0;
while (r - l >= k && curB - preB >= 2) {
t[preA & 1][preB & 1] = Math.min(t[preA & 1][preB & 1], preA - preB);
l++;
preA += s[l] === a ? 1 : 0;
preB += s[l] === b ? 1 : 0;
}
ans = Math.max(ans, curA - curB - t[(curA & 1) ^ 1][curB & 1]);
}
}
}
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(k)
Approach Breakdown
BRUTE FORCE
O(n × k) time
O(1) space
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
SLIDING WINDOW
O(n) time
O(k) space
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Shortcut: Each element enters and exits the window once → O(n) amortized, regardless of window size.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Shrinking the window only once
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.