-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy path1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js
59 lines (53 loc) · 1.8 KB
/
1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 1737. Change Minimum Characters to Satisfy One of Three Conditions
* https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {string} a
* @param {string} b
* @return {number}
*/
var minCharacters = function(a, b) {
const aFreq = getFrequency(a);
const bFreq = getFrequency(b);
const condition1 = operationsForCondition1(aFreq, bFreq);
const condition2 = operationsForCondition1(bFreq, aFreq);
const condition3 = operationsForCondition3(aFreq, bFreq);
return Math.min(condition1, condition2, condition3);
function getFrequency(str) {
const freq = Array(26).fill(0);
for (const char of str) {
freq[char.charCodeAt(0) - 97]++;
}
return freq;
}
function operationsForCondition1(aFreq, bFreq) {
let minOps = Infinity;
for (let i = 0; i < 25; i++) {
let ops = 0;
for (let j = 0; j <= i; j++) ops += aFreq[j];
for (let j = i + 1; j < 26; j++) ops += bFreq[j];
minOps = Math.min(minOps, ops);
}
return minOps;
}
function operationsForCondition3(aFreq, bFreq) {
let minOps = Infinity;
for (let i = 0; i < 26; i++) {
const ops = a.length + b.length - aFreq[i] - bFreq[i];
minOps = Math.min(minOps, ops);
}
return minOps;
}
};