← Questions

Best-matching binary pattern with wildcards

0
GoogleCodingLast asked Jan 2026

A coding interview question asked in Google's onsite coding round, last asked Jan 2026. It tests strings, tries and dynamic programming.

You get a list of patterns over the characters 0, 1 and ?, where ? matches either bit. Given a query string of bits, return the pattern that matches it best. A pattern matches a query of the same length when every non-wildcard character equals the query's character at that position. The best match is the matching pattern with the fewest wildcards; ties go to the pattern that appears first in the list.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • PatternMatcher(patterns: list[str]) — preprocesses the patterns.
  • best_match(query: str) -> str | None — the best matching pattern, or None when nothing matches.

Example

patterns = ["1??0", "10?0", "0???", "1010"]

best_match("1010")  ->  "1010"   # matches 1??0, 10?0 and 1010; 1010 has no wildcard
best_match("1000")  ->  "10?0"   # one wildcard beats two
best_match("1110")  ->  "1??0"
best_match("0111")  ->  "0???"
best_match("1111")  ->  None

Constraints

  • Up to 10^5 patterns of length up to 64, and up to 10^5 queries.
  • Queries must be faster than checking every pattern.

Clarifying questions

  • What makes one match better than another: fewest wildcards, an explicit priority, or the longest exact prefix?
  • Are all patterns and queries the same length?
  • Will the pattern list change after preprocessing?

What a strong answer covers

  • The baseline: check every pattern, O(P · L) per query.
  • A trie over pattern characters with three children per node (0, 1, ?); a query follows both its bit and the ? branch, and each leaf stores the best pattern ending there. The worst case is exponential in wildcard positions, so prune branches that cannot beat the best found so far (search the exact branch first, track wildcards used).
  • An alternative for fixed-length patterns: encode each pattern as a value mask and a care mask, so a match is (query & care) == value; group patterns by care mask and use a hash lookup per group.
  • Complexity of each in terms of patterns, length and distinct care masks, and tests for ties and no match.

Follow-ups

  • Each pattern carries an explicit priority instead of the wildcard rule.
  • Allow a trailing * that matches any remaining bits (variable-length matches, as in routing tables).
  • Patterns are added and removed while queries run.

Where it's asked

  • Google · Onsite coding · Last asked Jan 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

strings · tries · dynamic programming

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding