1551. Lamp Panel Switches

Medium3.5 points estimatedBitmaskEnumeration

A control panel has lamps lamps numbered from 0, stored as the bits of an integer, and a row of switches. Switch i toggles exactly the lamps whose bits are set in switches[i]. The current lamp state is the integer start (bit set means on). Pressing the same switch twice cancels out, so each switch is pressed either zero or one time, and the order of presses does not matter.

Return the smallest number of switches you must press so that all lamps lamps are on, i.e. the state equals (1 << lamps) - 1. If it is impossible, return -1. If every lamp is already on, the answer is 0.

Hint: there are at most 16 switches, so enumerate all 2^n subsets, XOR the chosen switch masks onto start, and keep the smallest subset size that works.

Intended complexity: O(2^n * n) time, O(1) extra space.

Example 1

Input:
switches = [1,2,4,3], start = 0, lamps = 3
Output:
2
Explanation:

Pressing the switches with masks 4 and 3 turns on lamps 2, 0 and 1, so two presses suffice and one is not enough.

Example 2

Input:
switches = [3,5,6], start = 0, lamps = 3
Output:
-1
Explanation:

Any combination of these three switches yields only masks with an even number of lamps, so all-on (7) is unreachable and the answer is -1.

Example 3

Input:
switches = [3,5,6], start = 7, lamps = 3
Output:
0
Explanation:

All three lamps are already on, so no switch needs to be pressed.

Constraints

1 ≤ switches.length ≤ 16

1 ≤ lamps ≤ 20

0 ≤ switches[i], start < 2^lamps

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(2^n * n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…