TryBugHunt
javaOtherEasy

Removing expired coupons crashes the coupon list

BugFind the bug and fix the code

What it should do

activeCoupons(coupons) removes every coupon code that starts with "OLD" and returns the rest in order, so activeCoupons(["OLD1", "NEW2", "NEW3"]) returns ["NEW2", "NEW3"].

What happens instead

activeCoupons(["OLD1", "NEW2", "NEW3"]) throws java.util.ConcurrentModificationException. activeCoupons(["SAVE10", "OLD5", "SPRING"]) happens to work.

import java.util.*;

public class Main {
    static List<String> activeCoupons(List<String> coupons) {
        for (String c : coupons) {
            if (c.startsWith("OLD")) {
                coupons.remove(c);
            }
        }
        return coupons;
    }
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the mutation and copying bugs pattern

Two references to one object, so changing one changes both; shallow copies of lists.

What you'll practise

An easy Java debugging exercise about mutation and copying bugs: two references to one object, so changing one changes both; shallow copies of lists.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

A for-each loop over an ArrayList uses an iterator, and the iterator checks on every step that the list has not been changed behind its back. Calling coupons.remove() inside the loop changes the list directly, so the next step throws ConcurrentModificationException. Oddly, removing the second-to-last element does not throw, because the loop thinks it has reached the end and stops, silently skipping the last item. That is why the bug can slip through some tests. Use removeIf, or an explicit Iterator and its own remove() method, to delete while walking a collection.

The pattern behind it: mutation and copying bugs.

More mutation and copying bugs to practise

Seen this error in your own code?

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/a5a5bcc1-72b4-432f-94cf-9e603b0bcca6" title="Debugging challenge: Removing expired coupons crashes the coupon list" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/a5a5bcc1-72b4-432f-94cf-9e603b0bcca6">TryBugHunt</a></p>