diff --git a/src/algorithms/string.py b/src/algorithms/string.py index 658439e..6074b42 100644 --- a/src/algorithms/string.py +++ b/src/algorithms/string.py @@ -41,9 +41,18 @@ def find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]: if not articles: return set() - common_tags = set(articles[0].get("tags", [])) - for article in articles[1:]: - common_tags.intersection_update(article.get("tags", [])) + # Pre-extract all tag lists for faster access and avoid repeated .get lookups + tag_lists = [article.get("tags", []) for article in articles] + + # If any tag list is empty, the intersection will be empty + if any(len(tags) == 0 for tags in tag_lists): + return set() + + # Sort tag_lists by length to start intersection from smallest, reducing work early + tag_lists.sort(key=len) + common_tags = set(tag_lists[0]) + for tags in tag_lists[1:]: + common_tags.intersection_update(tags) if not common_tags: break return common_tags