KatInterview

Build a Dynamic IP Address Filter with CIDR and Range Support

Data Structure DesignModel answer
MediumModel answerData Structure Designnetworkingdata-structuresheaps

Last updated

Implement a low-latency IP rule matcher supporting CIDR blocks and numeric ranges with conflict resolution based on specificity and recency.

You need to build a system that determines whether to allow or block IPv4 addresses based on configurable rules. Each rule specifies an action (accept or deny) and applies to either:

  • A CIDR block (e.g., 192.168.0.0/16)
  • An inclusive IP range (e.g., 10.0.0.1-10.0.0.50)
  • A single IP address

Your implementation must support three operations:

  1. addRule(action, specification) — Register a new rule
  2. removeRule(action, specification) — Delete the most recently added matching rule
  3. query(ip) — Return "accept" or "deny" for the given IP

When multiple rules match an IP address, apply these tiebreakers in order:

  1. Specificity: Prefer the rule covering the smallest address range
  2. Recency: If ranges are equal in size, prefer the most recently added rule
  3. Default: If no rules match, return "deny"

Your design should handle up to 100,000 rules efficiently with low query latency.

Provide:

  • Data structure choices and their rationale
  • Implementation with time and space complexity analysis
  • Discussion of edge cases (especially around bitwise operations and IP parsing)
  • Comparison of alternative approaches for this problem

Hints

Hint 1

Any numeric IP range can be decomposed into a small set of aligned CIDR blocks — this makes indexing much easier

Hint 2

Use a min-heap per CIDR block keyed by (original_rule_size, -rule_timestamp) to efficiently find the best matching rule

Hint 3

An IP address belongs to exactly one CIDR block at each prefix length (0 through 32), so checking all 33 possible blocks covers every applicable rule