Check whether a server is in an allow-list
Problem statement
An allow-list is a set of names that are permitted, and everything else is blocked. A set is the right tool for it: asking "is this name in the set?" stays quick no matter how many names the set holds, while a list has to check its items one by one.
Common mistake: comparing the name to the whole set.
Wrong: if name == allow_list:This asks whether the name is equal to the entire set, which is never true. To ask "is it inside the set?", use the membership check: in in Python, .contains() in Java, .count() in C++.
Your task: given the allow-list {"web-01", "web-02", "db-01"}, check the names "web-02" and "cache-09". Print each name followed by allowed or blocked.
Expected output:
web-02: allowedcache-09: blockedApproach
Loop over the names and check each one against the set:
- Python:
name in allow_list - Java:
allowList.contains(name), using aHashSet. Order does not matter here, since you only look names up. - C++:
allowList.count(name) > 0, using anunordered_set.countgives1if the name is in the set and0if not.
DSA connection: checking a hash set takes roughly the same time however big the set gets, which is why it beats scanning a list.
allow_list = {"web-01", "web-02", "db-01"}
for name in ["web-02", "cache-09"]:
if name in allow_list:
print(f"{name}: allowed")
else:
print(f"{name}: blocked")