# Right of Way

> Every packet asks the same question of the firewall. Answer it the way the table intends.

Canonical URL: <https://datadriven.io/problems/right_of_way>

Domain: Python · Difficulty: medium · Seniority: mid · Asked in: Okta

## Problem

The edge proxy's runtime has no `ipaddress` module, so CIDR containment is the code's own job. Each source IP in `requests` takes the action of the most specific block in `rules` that contains it, with a later rule overriding an earlier one of equal specificity, and the verdicts come back in arrival order.

## Example 1

Input:

```
rules = [["0.0.0.0/0","allow"],["192.168.0.0/16","block"],["192.168.1.0/24","allow"]], requests = ["192.168.1.5","192.168.2.5","10.0.0.1"]
```

Output:

```
["allow","block","allow"]
```

## Example 2

Input:

```
rules = [["10.0.0.0/8","block"]], requests = ["10.1.2.3","11.0.0.1"]
```

Output:

```
["block","allow"]
```

## Worked solution and explanation

### Why this problem exists in real interviews

This is longest-prefix match wearing an allow/block costume: the same lookup every router and firewall runs on every packet. The skill being probed is whether you treat a CIDR as an integer-and-mask comparison rather than a string prefix, and whether you get the precedence exactly right. More specific beats less specific regardless of table order, equal specificity falls to the later rule, and an unmatched address defaults open. Get the precedence wrong and a narrow /24 block is silently overridden by a broad /8 allow listed after it. Candidates who do string matching on '192.168.' break the moment a prefix is not a multiple of 8.

---

### Break down the requirements

#### Step 1: Turn each dotted quad into a 32-bit integer

Split on '.' and shift each octet into place: `(a << 24) | (b << 16) | (c << 8) | d`. Now containment is pure arithmetic with no string games, and a /17 or /23 prefix is no harder than a /8.

#### Step 2: Precompute a mask per rule

A /p prefix means the top p bits matter. Build `mask = (0xFFFFFFFF << (32 - p)) & 0xFFFFFFFF` and store `network & mask`. An IP matches when `ip_int & mask` equals that masked network. A /0 gives a mask of 0, which matches everything: that is the default route.

#### Step 3: Pick the winner with a single comparison

For each request, scan the rules while tracking `best_prefix`. Accept a matching rule when its prefix is greater than or equal to the current best. Greater handles 'more specific wins'. Equal, because you scan in table order, hands ties to the later rule. Start `best_prefix` at -1 and `decision` at 'allow' so an unmatched IP falls through to the default.

---

### The solution

**Integer-and-mask longest-prefix match with order-aware ties**

```python
def filter_requests(rules, requests):
    def to_int(ip):
        a, b, c, d = (int(part) for part in ip.split('.'))
        return (a << 24) | (b << 16) | (c << 8) | d

    parsed = []
    for cidr, action in rules:
        network, prefix = cidr.split('/')
        prefix = int(prefix)
        mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF if prefix else 0
        parsed.append((to_int(network) & mask, mask, prefix, action))

    results = []
    for ip in requests:
        ip_int = to_int(ip)
        best_prefix = -1
        decision = 'allow'
        for network, mask, prefix, action in parsed:
            if ip_int & mask == network and prefix >= best_prefix:
                best_prefix = prefix
                decision = action
        results.append(decision)
    return results
```

> **A flat scan is the right baseline at this scale**
>
> Parsing is O(R) over the rule table. Each request scans every rule, so the query phase is O(Q * R), and space is O(R) for the parsed table. A real firewall with thousands of rules and millions of requests swaps the flat scan for a binary trie (Patricia/radix) with O(prefix-length) lookups. At interview scale, the flat scan is the clear, correct baseline.

**String prefix matching (broken)**

`ip.startswith('192.168.')` only works when the prefix lands on a dot boundary (/8, /16, /24). A /20 or /27 rule silently never matches, and '10.1.1.1' wrongly matches a rule meant for '10.11.0.0/16'. It passes the easy tests and fails in production.

**Integer mask (correct)**

`ip_int & mask == network` compares exactly the top p bits for any p from 0 to 32. It does not depend on dot boundaries, and the same lines handle /0 (match all) and /32 (single host) with no special cases.

> **`>=` is the tie-break, not a typo**
>
> Writing `prefix > best_prefix` means that with two equally specific rules the first one wins and stays, so a later override never takes effect. The tie goes to the later rule, which is exactly what `>=` gives you because the scan runs in table order. The other classic miss is starting `decision` at 'block', which inverts the default-allow contract.

> **Say the precedence model before you code**
>
> State the precedence model out loud before coding: most specific wins, ties go to the later rule, default is allow. Then reach for integer masks rather than string slicing, and name /0 as the default route and /32 as a single host. Asking whether rules can be IPv6, or whether the table is hot-reloaded, signals you have seen this in a real proxy.

---

## Common follow-up questions

- The table has 50,000 rules and you serve a million requests a second. How do you make lookups sublinear in the rule count? _(Tests knowledge of Patricia/radix tries for longest-prefix match and why a flat scan stops scaling.)_
- How would you extend this to IPv6 without rewriting the matching logic? _(Tests generalizing 32-bit masks to 128-bit integers and keeping the mask comparison engine-agnostic.)_
- Rules now arrive as a live stream of additions and deletions. How do you keep the lookup structure consistent without blocking reads? _(Tests incremental trie updates, copy-on-write snapshots, or versioned tables for concurrent read/update.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/right_of_way)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). DataDriven is the data engineering interview community. Live code execution in SQL, Python, and Spark sandboxes. Every feature is open to every member.