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 to Satisfy Conditions INPUT String a = "aba" a b a String b = "caa" c a a Frequency Count: a: {a:2, b:1} b: {c:1, a:2} Alphabet Order: a < b < c < ... < z Goal: Min ops for 3 conditions ALGORITHM STEPS 1 Count frequencies Build freq arrays for a, b 2 Condition 3: Same char Cost = len(a)+len(b) - max freq 3 Condition 1: a < b Try each split point b-z 4 Condition 2: b < a Same logic, swap roles Try split at 'b': Cond1: a all < 'b', b all >= 'b' a: change b(1) = 1 op b: change a,a(2) = 2 ops Total = 3 Cond3: all 'a' = 6-4 = 2 Min = 2 [OK] FINAL RESULT Best: Condition 3 Make both strings all 'a' Before: a b a c a a After (2 ops): a a a a a a Output 2 [OK] Minimum operations = 2 Both strings: all 'a' Condition 3 satisfied! Key Insight: Use prefix sums to efficiently count chars below/at each threshold. For conditions 1 and 2, try all 25 possible split points (b to z). For condition 3, find the most frequent char across both strings. Time: O(n + 26), Space: O(26) = O(1). Single pass through each string! TutorialsPoint - Change Minimum Characters to Satisfy One of Three Conditions | Single Pass Optimized
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