Change Minimum Characters to Satisfy One of Three Conditions - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: a = "aba", b = "caa"
Output: 2
💡 Note: We can make a < b by changing 'a' to 'b' in string a (1 op) and 'a' to 'c' in string b (1 op), giving us "bbb" < "ccc". Total: 2 operations.
Example 2 — Make Identical
$ Input: a = "dabadd", b = "cda"
Output: 3
💡 Note: Best option is to make both strings contain only 'd': change 'a','b','a' in first string (3 ops) and 'c','a' in second string (2 ops), but we can make both 'a' with only 3 total operations.
Example 3 — Already Ordered
$ Input: a = "aaa", b = "bbb"
Output: 0
💡 Note: String a already has all characters less than all characters in string b, so no operations needed.

Constraints

  • 1 ≤ a.length, b.length ≤ 105
  • a and b consist only of lowercase English letters

Visualization

Tap to expand
Change Minimum Characters: Find Best Strategya = "aba"b = "caa"Three Possible Conditions:Condition 1: All a < All bCondition 2: All b < All aCondition 3: Both IdenticalCost: 3 operationsCost: 4 operationsCost: 2 operations ✓Minimum: 2 operations
Understanding the Visualization
1
Input
Two strings a="aba", b="caa" with mixed character order
2
Process
Try 3 conditions: a<b, b<a, or both identical
3
Output
Minimum operations needed: 2
Key Takeaway
🎯 Key Insight: Find the optimal boundary or target character that minimizes changes across all three possible conditions
Asked in
Google 15 Facebook 12 Microsoft 8
55.4K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen