All files / problems/bulbsSwitch index.ts

100% Statements 25/25
100% Branches 7/7
100% Functions 3/3
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 261x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 1x 1x 3x 3x 3x 14x 14x 14x 5x 5x 14x 3x 3x 3x  
// Problem Discussion
// Given N bulbs, either on (1) or off (0).
// Turning on ith bulb causes all remaining bulbs on the right to flip.
// Find the min number of switches to turn all the bulbs on.
// • Constraints:
// • 1 < N < 1e5
// • A[i] = {0, 1}
 
const isEven = (n: number): boolean => {
  return n % 2 === 0;
};
 
export const bulbsSwitch = (bulbs: number[]): number => {
  let cost = 0;
 
  for (const bulb of bulbs) {
    const bulbState = isEven(cost) ? !!bulb : !!!bulb;
 
    if (!bulbState) {
      cost++;
    }
  }
 
  return cost;
};