KatInterview

Pick the Tightest Wildcard Mask for a Bit String

StringsAuto-graded · 21 test cases
EasyAuto-gradedStringsstringspattern-matchinglinear-scan

Last updated

Scan a list of 0/1/? templates, keep those that fit a bit string, and return the one with the fewest wildcards, breaking ties by earliest position.

Tightest Template Match

You are given a list of templates and a single target bit string.

  • Each template is a string made of the characters '0', '1' and '?'.
  • The target is a string made only of '0' and '1'.

A template fits the target when both of the following hold:

  1. The template and the target have the same length.
  2. At every position, the template character is either '?' or equal to the target character at that position.

Among all templates that fit, return the tightest one, chosen by these rules in order:

  1. Prefer the template with the fewest '?' characters.
  2. If several templates are still tied, prefer the one that appears earliest in the input list.

If no template fits the target, return None.

The returned value is the template string itself, exactly as given in the list.

Constraints

  • 0 <= len(templates) <= 10,000
  • Templates contain only the characters '0', '1' and '?'.
  • The target contains only '0' and '1'.
  • Templates may have different lengths from the target; those never fit.
  • Duplicate templates may appear in the list.
  • The function returns a str, or None when nothing fits.

Examples

Example 1

Input: tightest_template(['0?1', '1?1', '011'], '011')

Output: '011'

Example 2

Input: tightest_template(['0?0', '?10'], '000')

Output: '0?0'

Example 3

Input: tightest_template(['???', '101', '1?1', '101'], '101')

Output: '101'

Hints

Hint 1

Each template can be judged independently of all the others, so a single pass over the list is enough.

Hint 2

A template of a different length can never fit. Check the length explicitly rather than relying on a pairwise loop that stops at the shorter string.

Hint 3

Rank fitting templates by the pair (number of '?', index in list). Replace your current best only when the new pair is strictly smaller, so earlier templates win ties.