LeetCode: Change Minimum Characters To Satisfy One Of Three Conditions Solution

1var minCharacters = function (a, b) {
2 const convertToArrayOfCharCode = str =>
3 str.split("").map((_, i) => str.charCodeAt(i) - 97)
4
5 // min step for a < b
6 const sol1 = (a, b) => {
7 let res = Infinity
8
9 // tricky part to make it strictly "<"
10 for (let i = 1; i < 26; i++) {
11 let count = 0
12 for (const ai of a) count += i <= ai
13 for (const bi of b) count += i > bi
14 res = Math.min(res, count)
15 }
16 return res
17 }
18
19 // min step to make a = b
20 const sol3 = (a, b) => {
21 let res = Infinity
22
23 for (let i = 0; i < 26; i++) {
24 let count = 0
25 for (const ai of a) count += i !== ai
26 for (const bi of b) count += i !== bi
27 res = Math.min(res, count)
28 }
29 return res
30 }
31
32 a = convertToArrayOfCharCode(a)
33 b = convertToArrayOfCharCode(b)
34 return Math.min(sol1(a, b), sol1(b, a), sol3(a, b))
35}

Comments

Loading comments...

Tags

leetcode

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Latest Time By Replacing Hidden Digits

HoningJS

Search Posts