1553. Answer Key Detective

Medium3.5 points estimatedBitmaskEnumerationString

A true/false quiz has q questions. The teacher lost the answer key but kept the graded sheets: answers[i] is student i's sheet, a string of length q made of 'T' and 'F', and scores[i] is the number of questions that student answered correctly. A key is consistent if, for every student, it agrees with that student's sheet in exactly scores[i] positions.

Return the number of different keys (strings of q letters 'T'/'F') that are consistent with all students. Return 0 if no key fits.

Hint: encode each sheet as a q-bit mask, loop over all 2^q candidate keys, and compare q - popcount(key XOR sheet) with the student's score.

Intended complexity: O(2^q * s) time where s is the number of students, and O(s) space.

Example 1

Input:
answers = ["TTF","TFF"], scores = [3,2]
Output:
1
Explanation:

The key must equal the first sheet TTF (3 correct); it then matches TFF in two positions, so exactly one key works.

Example 2

Input:
answers = ["T","F"], scores = [1,1]
Output:
0
Explanation:

With one question, a key can match only one of the two opposite sheets, so no key gives both students a score of 1.

Constraints

1 ≤ q ≤ 15 (all answers[i].length == q)

1 ≤ answers.length ≤ 50

0 ≤ scores[i] ≤ q

answers[i] consists of 'T' and 'F'.

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^q * s)
Space
O(s)

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…