Change Minimum Characters to Satisfy One of Three Conditions Problem
#1737
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1737.
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
ais strictly less than every letter inbin the alphabet. - Every letter in
bis strictly less than every letter inain the alphabet. - Both
aandbconsist 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 <= 10^5aandbconsist only of lowercase letters.
Solution
Approach: Letter Counts and Trying Every Boundary
Count how often each of the 26 letters occurs in a and in b. Every one of the three conditions can then be priced from these counts alone.
- Condition 3 (only one distinct letter in total): pick the letter
cthat everything becomes. All characters other thanc, in both strings, must change, which costsm + n - cnt_a[c] - cnt_b[c]. Try everyc. - Condition 1 (every letter of
ais smaller than every letter ofb): choose a boundary lettercfrombtoz. Letters ofathat arecor larger must change, and letters ofbthat are smaller thancmust change. Starting atamakes no sense (nothing is smaller), so trycfrombtozand keep the cheapest. - Condition 2 is condition 1 with the strings swapped.
The answer is the smallest of the three cases.
Complexity: O(m + n + C2) time, where C = 26 is the alphabet size, and O(C) extra space.
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