1859. Change Minimum Characters to Satisfy One of Three Conditions
My accepted C++ solution to LeetCode problem 1859, Change Minimum Characters to Satisfy One of Three Conditions, running in 9ms.
- Difficulty: Medium
- C++
- Runtime 9ms
- Memory 17.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 9ms, memory 17.6MB, accepted 2025-12-27.
class Solution {
public:
int minCharacters(string a, string b) {
int m = a.size(), n = b.size();
vector<int> ca(26), cb(26);
for (char c : a) ca[c - 'a']++;
for (char c : b) cb[c - 'a']++;
int res = m + n;
// Condition 3: make both strings same character
for (int i = 0; i < 26; i++) {
res = min(res, m + n - ca[i] - cb[i]);
}
// Conditions 1 & 2: prefix sum approach
int preA = 0, preB = 0;
for (int i = 0; i < 25; i++) {
preA += ca[i];
preB += cb[i];
// Condition 1: all a < all b, so a has chars [0,i], b has chars [i+1,25]
res = min(res, (m - preA) + preB);
// Condition 2: all b < all a
res = min(res, (n - preB) + preA);
}
return res;
}
};