|
| 1 | +/** |
| 2 | + * 1737. Change Minimum Characters to Satisfy One of Three Conditions |
| 3 | + * https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two strings a and b that consist of lowercase letters. In one operation, you can |
| 7 | + * change any character in a or b to any lowercase letter. |
| 8 | + * |
| 9 | + * Your goal is to satisfy one of the following three conditions: |
| 10 | + * - Every letter in a is strictly less than every letter in b in the alphabet. |
| 11 | + * - Every letter in b is strictly less than every letter in a in the alphabet. |
| 12 | + * - Both a and b consist of only one distinct letter. |
| 13 | + * |
| 14 | + * Return the minimum number of operations needed to achieve your goal. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string} a |
| 19 | + * @param {string} b |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var minCharacters = function(a, b) { |
| 23 | + const aFreq = getFrequency(a); |
| 24 | + const bFreq = getFrequency(b); |
| 25 | + |
| 26 | + const condition1 = operationsForCondition1(aFreq, bFreq); |
| 27 | + const condition2 = operationsForCondition1(bFreq, aFreq); |
| 28 | + const condition3 = operationsForCondition3(aFreq, bFreq); |
| 29 | + |
| 30 | + return Math.min(condition1, condition2, condition3); |
| 31 | + |
| 32 | + function getFrequency(str) { |
| 33 | + const freq = Array(26).fill(0); |
| 34 | + for (const char of str) { |
| 35 | + freq[char.charCodeAt(0) - 97]++; |
| 36 | + } |
| 37 | + return freq; |
| 38 | + } |
| 39 | + |
| 40 | + function operationsForCondition1(aFreq, bFreq) { |
| 41 | + let minOps = Infinity; |
| 42 | + for (let i = 0; i < 25; i++) { |
| 43 | + let ops = 0; |
| 44 | + for (let j = 0; j <= i; j++) ops += aFreq[j]; |
| 45 | + for (let j = i + 1; j < 26; j++) ops += bFreq[j]; |
| 46 | + minOps = Math.min(minOps, ops); |
| 47 | + } |
| 48 | + return minOps; |
| 49 | + } |
| 50 | + |
| 51 | + function operationsForCondition3(aFreq, bFreq) { |
| 52 | + let minOps = Infinity; |
| 53 | + for (let i = 0; i < 26; i++) { |
| 54 | + const ops = a.length + b.length - aFreq[i] - bFreq[i]; |
| 55 | + minOps = Math.min(minOps, ops); |
| 56 | + } |
| 57 | + return minOps; |
| 58 | + } |
| 59 | +}; |
0 commit comments