JSFiddle - React, Tailwind, and code Playground
JavaScript
const isConstant = arr => {
let result = true;
const limit = Math.floor(arr.length / 2) + 1; // halfway + 1
let i;
for (i=1; i<=arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
// We just found two different values! It's balanced and we're done.
result = false;
break;
}
else if (i >= limit - 1) {
// If we get this far, we know the array is constant and we're done.
break;
}
}
return { result, operations: i + 1 };
};
console.log(isConstant([0,0,0,0,0,0])); // 4
console.log(isConstant([1,1,1,1,1,1])); // 4
console.log(isConstant([1,1,1,1,0,0,0,0])); // 5
console.log(isConstant([1,1,1,1,1,1,1,1])); // 5
console.log(isConstant([0,1,0,1,0,1])); // 2
console.log(isConstant([0,0,0,1,1,1])); // 4