LeetCode: Minimum Changes To Make Alternating Binary String Solution
Approach
Create 2 possible output
s1
, s2
Calculate the number of steps from
s
to each of thoseFind min between 2 of them
Implementation
1/**2 * @param {string} s3 * @return {number}4 */5var minOperations = function (s) {6 const N = s.length7 const chars = s.split("").map(Number)8 const s1 = Array.from({ length: N }, (_, i) => (i % 2 === 0 ? 1 : 0))9 const s2 = Array.from({ length: N }, (_, i) => (i % 2 === 0 ? 0 : 1))10 return Math.min.apply(11 null,12 chars.reduce(13 (acc, el, i) => [14 acc[0] + (el !== s1[i] ? 1 : 0),15 acc[1] + (el !== s2[i] ? 1 : 0),16 ],17 [0, 0]18 )19 )20}
Comments
Loading comments...
Tags
leetcode
array
greedy
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: Count Number Of Homogenous Substrings
Feb 14, 2021