Code Logo

Duplicate Coupon Check with HashSet

Published at22 Apr 2026
Collections Framework Easy 0 views
Like0

A small shop is reviewing a list of coupon codes collected from a campaign form. The manager wants to know quickly whether the list contains any repeated code, because duplicates usually mean someone pasted the same entry more than once.

Your task is to return true if any coupon code appears at least twice. Return false if every code is unique.

For example, ["SAVE10", "NEW20", "SAVE10"] should return true because SAVE10 appears again. Meanwhile, ["A1", "B2", "C3"] should return false because every item is different.

This challenge is a natural introduction to HashSet, which is useful when you care about fast membership checks rather than preserving duplicates.

Example Input & Output

Example 1
Input
codes = ["SAVE10", "NEW20", "SAVE10"]
Output
true
Explanation

The code SAVE10 appears more than once.

Example 2
Input
codes = ["A1", "B2", "C3"]
Output
false
Explanation

Every coupon code is unique.

Example 3
Input
codes = ["ONE", "ONE"]
Output
true
Explanation

A repeated value should be detected immediately.

Algorithm Flow

Recommendation Algorithm Flow for Duplicate Coupon Check with HashSet
Recommendation Algorithm Flow for Duplicate Coupon Check with HashSet

Solution Approach

A HashSet works well here because it stores unique values only. As you scan the list from left to right, each coupon code can be checked against the set to see whether it has already appeared.

The pattern is straightforward. Start with an empty set. For each code, ask whether the set already contains it. If the answer is yes, you have found a duplicate and can return true immediately. If not, add the code to the set and continue.

The logic looks like this:

Set<String> seen = new HashSet<>();
for (String code : codes) {
    if (seen.contains(code)) {
        return true;
    }
    seen.add(code);
}
return false;

This is cleaner than comparing every code against every other code, which would do unnecessary repeated work. With a HashSet, the average lookup and insertion cost is constant, so the full solution runs in about O(n) time with O(n) extra space.

Best Answers

java - Approach 1
import java.util.List;
import java.util.Set;
import java.util.HashSet;

class Solution {
    public static boolean hasDuplicateCoupon(List<String> codes) {
        Set<String> seen = new HashSet<>();
        for (String code : codes) {
            if (seen.contains(code)) {
                return true;
            }
            seen.add(code);
        }
        return false;
    }
}