Problem Description
Given two strings a and b consisting of lowercase letters, you can change any character in either string to any lowercase letter in one operation. The goal is to achieve at least one of the following conditions:
- Every letter in a is strictly less than every letter in b.
- Every letter in b is strictly less than every letter in a.
- Both strings consist of only one distinct letter.
Return the minimum number of operations needed to reach one of these conditions.
Key Insights
- Count the frequency of each character in both strings.
- Use prefix sums over the alphabet (26 letters) to quickly determine how many changes are needed when forcing a string to only have characters up to a given letter, or starting from a letter.
- For condition 1, try all partition boundaries (from 'a' to 'y') where a is forced to letters ≤ some letter and b is forced to letters > that letter.
- For condition 2, reverse the roles compared to condition 1.
- For condition 3, check for each letter the cost to convert both strings entirely to that letter.
- Take the minimum operations among these three approaches.
Space and Time Complexity
Time Complexity: O(n + 26), essentially O(n) where n = |a| + |b| Space Complexity: O(1) extra space aside from input storage because frequency arrays and prefix sums use constant space (26 letters)
Solution
We first count the frequency of each lowercase letter in strings a and b. Then, build prefix sums for both such that:
- For a given letter index i (0 for 'a', 25 for 'z'), prefix[i] in a represents the total count of letters ≤ that letter.
- For condition 1, for each possible partition boundary (from 0 to 24), we force string a to only have letters ≤ i and string b to only have letters > i. The cost is the number of letters in a that are greater than i plus the number of letters in b that are ≤ i.
- Similarly, for condition 2, we force string b to only have letters ≤ i and string a to only have letters > i.
- For condition 3, for each letter, the cost is the entire length of a plus b minus its frequency, meaning convert every character in both strings to that letter.
- Finally, return the minimum cost among these computed values.
We now provide code in multiple languages with detailed comments.