Skip to content

Most Frequent Octet

01 · Question

Given a list of unique IPv4 addresses, return the most common first octet. If several octets tie, return any of them.

Example:

  • Input: ["203.0.113.10", "198.51.100.5", "192.0.2.5", "203.0.113.5"]
  • Output: 203

02 · Analysis

An IPv4 octet is an 8-bit number, so it has only 256 possible values. Store each count directly at its octet index in a 256-element array.

Processing the addresses takes O(n)O(n) time. The count array uses O(256)=O(1)O(256) = O(1) extra space, regardless of the number of addresses.

03 · Solution

Reference solution

1def most_frequent_octet(ips):
2 counts = [0] * 256
3 best = 0
4
5 for ip in ips:
6 octet = int(ip.split(".", 1)[0])
7 counts[octet] += 1
8 if counts[octet] > counts[best]:
9 best = octet
10
11 return best