The lab switches
- O(2ⁿ) · Legendary
- Full plan
- Python
- JavaScript
- recursion
- lists
Problem
In the old lab, nobody knows which switch goes to which lamp. Anders Lund, the technician, has finally worked it out: each switch is wired to several lamps, and pressing it flips all of them: the ones that are off turn on and the ones that are on turn off. Now he wants to turn them all on by pressing as few switches as possible.
Write a function that takes n, the number of lamps (1 or more; they are numbered 0 to n - 1), and switches, a list where each item is the list of lamps that switch flips (no lamp repeated; the list of switches may be empty). All lamps start off, and pressing a switch flips each of its lamps: a lamp that is off turns on and one that is on turns off. Each switch is pressed once or not at all, and the order doesn't matter. Return a whole number: the fewest switches you need to press so that all the lamps are on at the same time, or -1 if there is no way. With 3 lamps and switches [[0, 1], [1, 2], [1]] you have to press all three: the first turns on 0 and 1, the second turns on 2 but turns off 1, and the third turns 1 back on. Return 3. With 3 lamps and switches [[0, 1], [1, 2]], lamp 1 always ends up off if you turn on 0 and 2, so return -1.
Examples
The example
3, [[0, 1], [1, 2], [1]] → 3
There is no way
3, [[0, 1], [1, 2]] → -1
The one that lights the most doesn't go first
6, [[0, 1, 2, 3], [0, 1, 2], [3, 4, 5], [4], [5]] → 2
A single one turns them all on
4, [[0, 1, 2, 3]] → 1
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def fewest_presses(n, switches):
passJavaScript
function fewestPresses(n, switches) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.
More O(2ⁿ) challenges
- The morning batchesrecursion · lists · dictionaries
- The necklace both threads sharerecursion · strings · indexes
- The Pompeii graffitorecursion · strings · indexes
- The rowers of Puntrecursion · lists · comparisons
- The satellite's counterweightsrecursion · lists · operations
- The subway routesrecursion · lists · loops