As reported: Google SDE 2 / L4 phone screen (January 2025): four patterns
F1 "*",F2 "192.168.*",F3 "192.168.2.*",F4 "192.168.2.1"; for the queries192.168.7.1,192.168.2.1,192.168.2.7,192.167.1.1return the name of the most precisely matching pattern:[F2, F4, F3, F1]. Solved optimally with a trie. Also asked in a Google L4 onsite round 1 (Bangalore, December 2024): patterns that may end with a wildcard, such as192.168.1.*; check whether a query matches any pattern — patterns["192.124.168.*", "192.124.64.*", "192.12.16.8", "192.124.6.1"], query192.124.168.1→ true,192.124.16.8→ false. A trie was used there; the follow-up extended it to several lists of patterns and to processing two IPs together.
An IPv4 address is four numbers 0–255 separated by dots. A pattern is either a full address (192.168.2.1), or one to three leading numbers followed by .* (192.168.*), or just *. The * stands for all the remaining numbers: 192.168.* matches every address that starts with 192.168., and * matches every address. Each pattern has a name.
Part 1. For a query address, decide whether any pattern matches it.
Part 2. For each query address, return the name of the most precise matching pattern — the one that fixes the most leading numbers (a full address is the most precise) — or NONE if no pattern matches.
Example 1
F1 * F2 192.168.* F3 192.168.2.* F4 192.168.2.1
192.168.7.1 -> F2
192.168.2.1 -> F4
192.168.2.7 -> F3
192.167.1.1 -> F1
Example 2
P1 192.124.168.* P2 192.124.64.* P3 192.12.16.8 P4 192.124.6.1
192.124.168.1 -> P1 (matches: true)
192.124.16.8 -> NONE (matches: false)
Follow-ups
- Several lists of patterns.
- Processing two IPs together.
Clarifications
- Numbers are compared whole:
1.2.*does not match12.2.3.4or1.20.3.4. - Patterns are distinct, so the most precise match is unique.
Constraints: 1 ≤ number of patterns ≤ 2 · 10^4; 1 ≤ number of queries ≤ 5 · 10^4; names are short strings without spaces.
Code runner format: the input is the number of patterns, then one line name pattern per pattern, then the number of queries and one address per line. Implement mostPreciseMatch(patterns, queries) with patterns[i] = [name, pattern], returning one name (or NONE) per query. The harness prints one per line. Part 1's answer is "the result is not NONE".