Subnetting and subnet masks in Computer Networks - Time & Space Complexity
When working with subnetting and subnet masks, it is helpful to understand how the time needed to calculate or apply subnet masks changes as the network size grows.
We want to know how the effort to divide a network into smaller parts grows when the number of IP addresses or subnets increases.
Analyze the time complexity of the following subnet mask calculation process.
function calculateSubnetMask(totalHosts) {
let bits = 0;
while ((2 ** bits - 2) < totalHosts) {
bits++;
}
return 32 - bits;
}
This code finds the smallest subnet mask that can hold the required number of hosts by increasing bits until enough addresses are available.
Look at what repeats as input grows.
- Primary operation: The while loop that increases bits to find enough addresses.
- How many times: The loop runs until 2^bits - 2 is at least the number of hosts.
The number of loop steps grows slowly as the number of hosts increases because each step doubles the address space.
| Input Size (Hosts) | Approx. Loop Iterations |
|---|---|
| 10 | 5 |
| 100 | 8 |
| 1000 | 11 |
Pattern observation: The loop count increases slowly, roughly adding one step each time the host count doubles many times.
Time Complexity: O(log n)
This means the time to find the subnet mask grows slowly as the number of hosts increases, roughly proportional to the logarithm of the input size.
[X] Wrong: "The time to calculate subnet masks grows directly with the number of hosts."
[OK] Correct: Because the calculation uses powers of two, the loop only runs a few times even for large host numbers, so it grows much slower than the host count.
Understanding how subnet mask calculations scale helps you think clearly about network design and efficiency, a useful skill in many technical roles.
What if we changed the calculation to check every possible subnet mask from 32 down to 0 instead of increasing bits? How would the time complexity change?