Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active May 31, 2020 03:40
Show Gist options
  • Save mgtitimoli/38e8eeb0ac2a1a7e7750906b60ef0b34 to your computer and use it in GitHub Desktop.
Save mgtitimoli/38e8eeb0ac2a1a7e7750906b60ef0b34 to your computer and use it in GitHub Desktop.
Find the minimum number of flips to get an alternating array of binary numbers

Exercise

Given an array of binary numbers, find the minimum number of flips (inversions) required to get an alternating version of it.

Solution

Given that we are dealing with binary numbers, there are 2 possible alternating versions of it, the one that starts with 0, and the one that starts with 1. This means that the input array should be compared with these 2 possibilities, get the number of required flips on each of them, and finally the result will be the minimum of these 2 counts.

const flip = binNumber => binNumber === 0 ? 1 : 0;
const reduceFlipsForAlternating = ({expectedBinNumber, flips}, binNumber) => ({
expectedBinNumber: flip(expectedBinNumber),
flips: binNumber !== expectedBinNumber ? flips + 1 : flips,
});
const getFlipsForAlternating = (binNumbers, expectedBinNumber) =>
binNumbers.reduce(reduceFlipsForAlternating, {expectedBinNumber, flips: 0})
.flips;
const getMinFlipsForAlternating = binNumbers =>
binNumbers.length < 2
? 0
: Math.min(
getFlipsForAlternating(binNumbers, 0),
getFlipsForAlternating(binNumbers, 1)
);
export {getMinFlipsForAlternating};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment