Busiest Network Addresses With Tie-Inclusive Top Ten Cutoff
Arrays & HashingAuto-graded · 21 test casesLast updated
Normalize IPv4/IPv6 strings, skip invalid ones, count occurrences, and return the top ten addresses while keeping every address tied at the tenth-place frequency.
Busiest Addresses
You are given a list of strings, each meant to be the textual form of an IP address (IPv4 or IPv6). Report the most frequently seen addresses, keeping everyone tied at the cutoff.
Task
Implement a function that takes the list entries and returns a list of normalized address strings.
- Normalize each entry: strip leading and trailing whitespace, parse it as an IPv4 or IPv6 address, and convert it to its canonical compressed text form. For example,
2001:0db8::1and2001:db8:0:0:0:0:0:1are the same address and both become2001:db8::1. - Skip invalid entries. An entry that cannot be parsed as an IP address is ignored and counts toward nothing.
- Count how many entries map to each normalized address.
- Order the distinct addresses by descending count. Addresses with equal counts are ordered by their normalized string in ascending lexicographic (plain string comparison) order.
- Select:
- If there are at most ten distinct addresses, return all of them in that order.
- Otherwise, let
cutoffbe the count of the address in the tenth position of that order. Return every address whose count is at leastcutoff, in that same order. The result may therefore contain more than ten addresses.
If no entry is valid, return an empty list.
Follow-up to think about (not tested)
How would you solve this if the distinct-address map did not fit in memory? Consider hash-partitioning the stream to disk so equal addresses land in the same partition, counting each partition exactly, then applying a global threshold, and what to do about a skewed partition.
Constraints
0 <= len(entries) <= 10^5for the tested inputs.- Entries may be IPv4, IPv6 in any valid textual form, or arbitrary invalid text.
- Counts can be large, so do not assume a fixed small integer width in a general solution.
- Output uses the canonical compressed form of each address.
Examples
Example 1
Input: busiest_addresses(['192.168.1.1', '10.0.0.1', '192.168.1.1', '8.8.8.8', '10.0.0.1', '192.168.1.1'])
Output: ['192.168.1.1', '10.0.0.1', '8.8.8.8']
Example 2
Input: busiest_addresses(['2001:0db8::1', '2001:db8:0:0:0:0:0:1', 'bad-ip', '127.0.0.1', '127.0.0.1', '::1'])
Output: ['127.0.0.1', '2001:db8::1', '::1']
Example 3
Input: busiest_addresses(['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4', '5.5.5.5', '6.6.6.6', '7.7.7.7', '8.8.8.8', '9.9.9.9', '10.10.10.10', '11.11.11.11', '12.12.12.12'])
Output: ['1.1.1.1', '10.10.10.10', '11.11.11.11', '12.12.12.12', '2.2.2.2', '3.3.3.3', '4.4.4.4', '5.5.5.5', '6.6.6.6', '7.7.7.7', '8.8.8.8', '9.9.9.9']
Hints
Hint 1
Parsing and normalizing is the key to correct grouping: two different strings can denote the same address. Python's standard library has a module that parses and prints addresses canonically.
Hint 2
Count normalized strings in a dictionary, then sort the (address, count) pairs by the key (-count, address) so ties are resolved deterministically.
Hint 3
Once sorted, look at the tenth item's count and keep everything whose count is at least that value. If there are ten or fewer distinct addresses, just return them all.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Walk through the entries once. For each one, strip whitespace and parse it with
ipaddress.ip_address, then take thecompressedtext. This makes different spellings of the same address identical. Entries that raise a parsing error are skipped. - Tally the normalized strings in a
Counter. - Sort the
(address, count)pairs by(-count, address). This gives descending frequency with a deterministic ascending string tie-break. - If there are ten or fewer distinct addresses, return all of them. Otherwise read the count of the tenth item as
cutoffand return every address whose count is at leastcutoff. Because the list is sorted by count, this is a prefix of the sorted list.
Why it is correct
Normalization ensures counts are per real address rather than per spelling. Sorting by count puts the tenth-ranked address at index 9, so its count is exactly the cutoff. Any address with an equal or higher count must be included, and all of these sit at the front of the sorted list, so filtering by count >= cutoff keeps all ties and nothing else.
Complexity
With n entries and d distinct valid addresses: time is O(n + d log d), space is O(d). A size-ten heap could find the cutoff in O(d log 10), but you still need a pass to collect ties and sort the result, so the simple sort is fine here.
Out-of-memory extension
Hash-partition normalized addresses into P files on disk so equal addresses share a partition, and count each partition independently in memory. Track the global cutoff using a size-ten structure over all partition counts, then do a second pass over the per-partition count files to collect every address at or above the cutoff (so ties are not lost to a local top ten). A partition that is still too large because of skew can be re-partitioned with a different hash seed, while a single extremely hot address is simply one key with a large count.
Reference solution
from collections import Counter
import ipaddress
from typing import List
def busiest_addresses(entries: List[str]) -> List[str]:
counts = Counter()
for value in entries:
try:
address = ipaddress.ip_address(value.strip()).compressed
except (ValueError, TypeError, AttributeError):
continue
counts[address] += 1
ordered = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
if len(ordered) <= 10:
return [address for address, _ in ordered]
cutoff = ordered[9][1]
return [address for address, count in ordered if count >= cutoff]