Skip to the code
cf.
+50 XP

#13 Fewest Switches to Light the Board

hard

A smart-home dashboard controls n lights, numbered 0 to n - 1, all starting off. Each switch in buttons is a list of light numbers; pressing it toggles each of those lights (off becomes on, on becomes off).

Each switch can be pressed at most once, and the order doesn't matter. Write fewestSwitches(n, buttons) that returns the smallest number of switches to press so that every light is on, or -1 if it can't be done.

Example 1

Input: n = 3, buttons = [[0,1],[1,2],[0],[2]]
Output: 2

Pressing [0, 1] and [2] lights all three. No single switch does.

Example 2

Input: n = 2, buttons = [[0],[0]]
Output: -1

No switch touches light 1, so it can never turn on.

Constraints

  • 1 <= n <= 10
  • 0 <= buttons.length <= 15
  • Each switch lists distinct light numbers from 0 to n - 1.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).