Securing Raspberry Pi (SSH keys, firewall) - Time & Space Complexity
When securing a Raspberry Pi using SSH keys and firewall rules, it is important to understand how the time to apply these security steps grows as the number of devices or rules increases.
We want to know how the work needed changes when we add more keys or firewall rules.
Analyze the time complexity of the following code snippet.
import os
# Add multiple SSH public keys to authorized_keys
for key in ssh_keys:
with open('/home/pi/.ssh/authorized_keys', 'a') as file:
file.write(key + '\n')
# Apply firewall rules from a list
for rule in firewall_rules:
os.system(f"sudo ufw allow {rule}")
This code adds each SSH key to the authorized keys file and applies each firewall rule one by one.
- Primary operation: Two loops that each run through lists of keys and firewall rules.
- How many times: Each loop runs once for every item in its list.
As the number of SSH keys or firewall rules grows, the time to add or apply them grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 keys + 10 rules) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: Doubling the number of keys and rules roughly doubles the work needed.
Time Complexity: O(n)
This means the time to secure the Raspberry Pi grows directly with the number of keys and firewall rules you add.
[X] Wrong: "Adding more SSH keys or firewall rules won't affect the time much because each step is quick."
[OK] Correct: Even if each step is fast, doing many steps adds up, so more keys or rules mean more total time.
Understanding how security setup time grows helps you plan and explain your approach clearly in real projects or interviews.
"What if we batch all firewall rules into one command instead of running one command per rule? How would the time complexity change?"