Leetcode #1737: Change Minimum Characters to Satisfy One of Three Conditions
In this guide, we solve Leetcode #1737 Change Minimum Characters to Satisfy One of Three Conditions in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Hash Table, String, Counting, Prefix Sum
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
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).
Python Solution
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
Complexity
The time complexity is , where and are the lengths of strings and respectively, and is the size of the character set. The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.