Find the longest matching wildcard IP pattern for a target address
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given a list of IPv4 patterns whose trailing octets may be wildcards and a target address, return the most specific pattern that matches the target, or an empty string. It tests longest-prefix matching over octets with a trie, plus careful handling of ties and the all-wildcard pattern.
Constraints
- 1 <= len(patterns) <= 10^4
- Each pattern and the target consist of exactly 4 dot-separated octets.
- Each octet is either * or an integer in the range [0, 255], written in plain decimal with no leading zeros.
- The target contains no wildcards.
- Wildcards only appear at the end of a pattern: once an octet is *, every later octet in that pattern is *.
Examples
Input: (['192.168.*.*', '192.168.1.*', '10.0.0.*', '192.*.*.*'], '192.168.1.100')
Expected Output: '192.168.1.*'
Explanation: Source example 1: the three-octet match beats the two-octet and one-octet matches, and 10.0.0.* fails on the first octet.
Input: (['10.0.0.1', '10.0.0.*', '10.0.*.*', '10.*.*.*'], '10.0.0.1')
Expected Output: '10.0.0.1'
Explanation: Source example 2: every pattern matches and the exact four-octet pattern fixes the most octets.
Hints
- Because a wildcard can only begin a suffix, the number of leading non-wildcard octets in a pattern is simply how many fixed octets it has.
- Every fixed octet has to agree with the target in the same position. Agreeing on the first few is not enough, and 1, 10 and 100 are different octets.
- The pattern *.*.*.* is a real match with zero octets, which is different from having no match at all.