Code Logo

Duplicate Tag Check with set()

Published at22 Apr 2026
Python Data Structures Easy 0 views
Like0

A storeroom clerk is reviewing a printed list of box tags before the afternoon shipment starts. Each box should have its own tag code, but sometimes the same code is written twice by mistake. The clerk wants a quick way to tell whether the list contains any duplicate tag at all.

Your task is to return True if at least one tag appears more than once in the list. If every tag is unique, return False.

For example, if the tags are ["A12", "B08", "A12"], the answer should be True because "A12" appears twice. If the tags are ["X1", "Y2", "Z3"], the answer should be False because no value is repeated.

This challenge is about spotting repeated membership, not counting how many times each item appears. As soon as the list contains a duplicate anywhere, the result should be True.

Example Input & Output

Example 1
Input
tags = ["A12", "B08", "A12"]
Output
True
Explanation

The tag "A12" appears more than once, so the result is True.

Example 2
Input
tags = []
Output
False
Explanation

An empty list has no repeated values.

Example 3
Input
tags = ["X1", "Y2", "Z3"]
Output
False
Explanation

Every tag is unique, so there is no duplicate to report.

Algorithm Flow

Recommendation Algorithm Flow for Duplicate Tag Check with set()
Recommendation Algorithm Flow for Duplicate Tag Check with set()

Solution Approach

This is a natural place to use a set because a set only keeps unique values. If you convert the list of tags into a set, any repeated tag automatically collapses into a single stored item.

That means a very compact solution is to compare sizes:

return len(tags) != len(set(tags))

If the original list and the set have the same length, then nothing was removed during conversion, so every tag was unique. If the set becomes shorter, that only happens because one or more tags were duplicates.

This works well because the problem only asks whether a duplicate exists, not which duplicate appeared first or how many times it appeared. The set gives exactly the uniqueness information we need.

You can also solve the problem with a loop and a seen set. Each time you read a tag, check whether it is already in seen. If it is, you can return True immediately. Otherwise, add it and continue. That version makes the process more visible, while the length-comparison version is shorter.

Either way, the key Python data-structure idea is the same: sets are excellent for membership and uniqueness checks. The runtime is about O(n) with normal hash behavior, and the extra space is proportional to the number of distinct tags stored in the set.

Best Answers

python - Approach 1
def has_duplicate_tags(tags):
    seen = set()
    for tag in tags:
        if tag in seen:
            return True
        seen.add(tag)
    return False