Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.
Your goal is to satisfy one of the following three conditions:
a is strictly less than every letter in b in the alphabet.b is strictly less than every letter in a in the alphabet.a and b consist of only one distinct letter.Return the minimum number of operations needed to achieve your goal.
Example 1:
Input: a = "aba", b = "caa" Output: 2 Explanation: Consider the best way to make each condition true: 1) Change b to "ccc" in 2 operations, then every letter in a is less than every letter in b. 2) Change a to "bbb" and b to "aaa" in 3 operations, then every letter in b is less than every letter in a. 3) Change a to "aaa" and b to "aaa" in 2 operations, then a and b consist of one distinct letter. The best way was done in 2 operations (either condition 1 or condition 3).
Example 2:
Input: a = "dabadd", b = "cda" Output: 3 Explanation: The best way is to make condition 1 true by changing b to "eee".
Constraints:
1 <= a.length, b.length <= 105a and b consist only of lowercase letters.Problem summary: You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter. Your goal is to satisfy one of the following three conditions: Every letter in a is strictly less than every letter in b in the alphabet. Every letter in b is strictly less than every letter in a in the alphabet. Both a and b consist of only one distinct letter. Return the minimum number of operations needed to achieve your goal.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map
"aba" "caa"
"dabadd" "cda"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1737: Change Minimum Characters to Satisfy One of Three Conditions
class Solution {
private int ans;
public int minCharacters(String a, String b) {
int m = a.length(), n = b.length();
int[] cnt1 = new int[26];
int[] cnt2 = new int[26];
for (int i = 0; i < m; ++i) {
++cnt1[a.charAt(i) - 'a'];
}
for (int i = 0; i < n; ++i) {
++cnt2[b.charAt(i) - 'a'];
}
ans = m + n;
for (int i = 0; i < 26; ++i) {
ans = Math.min(ans, m + n - cnt1[i] - cnt2[i]);
}
f(cnt1, cnt2);
f(cnt2, cnt1);
return ans;
}
private void f(int[] cnt1, int[] cnt2) {
for (int i = 1; i < 26; ++i) {
int t = 0;
for (int j = i; j < 26; ++j) {
t += cnt1[j];
}
for (int j = 0; j < i; ++j) {
t += cnt2[j];
}
ans = Math.min(ans, t);
}
}
}
// Accepted solution for LeetCode #1737: Change Minimum Characters to Satisfy One of Three Conditions
func minCharacters(a string, b string) int {
cnt1 := [26]int{}
cnt2 := [26]int{}
for _, c := range a {
cnt1[c-'a']++
}
for _, c := range b {
cnt2[c-'a']++
}
m, n := len(a), len(b)
ans := m + n
for i := 0; i < 26; i++ {
ans = min(ans, m+n-cnt1[i]-cnt2[i])
}
f := func(cnt1, cnt2 [26]int) {
for i := 1; i < 26; i++ {
t := 0
for j := i; j < 26; j++ {
t += cnt1[j]
}
for j := 0; j < i; j++ {
t += cnt2[j]
}
ans = min(ans, t)
}
}
f(cnt1, cnt2)
f(cnt2, cnt1)
return ans
}
# Accepted solution for LeetCode #1737: Change Minimum Characters to Satisfy One of Three Conditions
class Solution:
def minCharacters(self, a: str, b: str) -> int:
def f(cnt1, cnt2):
for i in range(1, 26):
t = sum(cnt1[i:]) + sum(cnt2[:i])
nonlocal ans
ans = min(ans, t)
m, n = len(a), len(b)
cnt1 = [0] * 26
cnt2 = [0] * 26
for c in a:
cnt1[ord(c) - ord('a')] += 1
for c in b:
cnt2[ord(c) - ord('a')] += 1
ans = m + n
for c1, c2 in zip(cnt1, cnt2):
ans = min(ans, m + n - c1 - c2)
f(cnt1, cnt2)
f(cnt2, cnt1)
return ans
// Accepted solution for LeetCode #1737: Change Minimum Characters to Satisfy One of Three Conditions
struct Solution;
impl Solution {
fn min_characters(a: String, b: String) -> i32 {
let a: Vec<u8> = a.bytes().collect();
let b: Vec<u8> = b.bytes().collect();
let count_a = Self::check(&a);
let count_b = Self::check(&b);
let mut prefix_a = vec![0; 26];
let mut prev_a = 0;
let mut prefix_b = vec![0; 26];
let mut prev_b = 0;
for i in 0..26 {
prefix_a[i] = prev_a;
prev_a += count_a[i];
prefix_b[i] = prev_b;
prev_b += count_b[i];
}
let mut postfix_a = vec![0; 26];
let mut next_a = 0;
let mut postfix_b = vec![0; 26];
let mut next_b = 0;
for i in (0..26).rev() {
postfix_a[i] = next_a;
next_a += count_a[i];
postfix_b[i] = next_b;
next_b += count_b[i];
}
let mut max = 0;
let mut max_a = 0;
let mut max_b = 0;
for i in 0..26 {
max_a = max_a.max(count_a[i]);
max_b = max_b.max(count_b[i]);
}
max = max.max(max_a + max_b);
for i in 1..26 {
max = max.max(prefix_a[i] + postfix_b[i - 1]);
max = max.max(prefix_b[i] + postfix_a[i - 1]);
}
(a.len() + b.len() - max) as i32
}
fn check(s: &[u8]) -> Vec<usize> {
let mut count: Vec<usize> = vec![0; 26];
for b in s {
count[(b - b'a') as usize] += 1;
}
count
}
}
#[test]
fn test() {
let a = "aba".to_string();
let b = "caa".to_string();
let res = 2;
assert_eq!(Solution::min_characters(a, b), res);
let a = "dabadd".to_string();
let b = "cda".to_string();
let res = 3;
assert_eq!(Solution::min_characters(a, b), res);
let a = "acac".to_string();
let b = "bd".to_string();
let res = 1;
assert_eq!(Solution::min_characters(a, b), res);
}
// Accepted solution for LeetCode #1737: Change Minimum Characters to Satisfy One of Three Conditions
function minCharacters(a: string, b: string): number {
const m = a.length,
n = b.length;
let count1 = new Array(26).fill(0);
let count2 = new Array(26).fill(0);
const base = 'a'.charCodeAt(0);
for (let char of a) {
count1[char.charCodeAt(0) - base]++;
}
for (let char of b) {
count2[char.charCodeAt(0) - base]++;
}
let pre1 = 0,
pre2 = 0;
let ans = m + n;
for (let i = 0; i < 25; i++) {
pre1 += count1[i];
pre2 += count2[i];
// case1, case2, case3
ans = Math.min(ans, m - pre1 + pre2, pre1 + n - pre2, m + n - count1[i] - count2[i]);
}
ans = Math.min(ans, m + n - count1[25] - count2[25]);
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan the rest of the array looking for a match. Two nested loops give n × (n−1)/2 comparisons = O(n²). No extra space since we only use loop indices.
One pass through the input, performing O(1) hash map lookups and insertions at each step. The hash map may store up to n entries in the worst case. This is the classic space-for-time tradeoff: O(n) extra memory eliminates an inner loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.