Drill

ProblemsJava › payments

Charge each request only once

mediumpaymentsHash mapsArraysSimulationJava

The payment webhook is delivered at least once, sometimes more. Each delivery carries an idempotency key, and a replay must not charge the customer twice.

applyOnce(events: list<Event>) → int

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int applyOnce(List<Event> events) {
    
}

Worked examples

CallResult
applyOnce(Main.<Event>ls(new Event("a", 100), new Event("b", 50), new Event("a", 100)))150
applyOnce(Main.<Event>ls(new Event("a", 100), new Event("a", -100)))100
applyOnce(Main.<Event>ls(new Event("x", 7)))7
applyOnce(Main.<Event>ls())0

Hint

Remember the keys you have already honoured.

Reference solution in Java
int applyOnce(List<Event> events) {
    Set<String> seen = new HashSet<>();
    int total = 0;
    for (Event e : events) {
        if (!seen.add(e.key)) continue;
        total += e.amount;
    }
    return total;
}

The same problem in another language

More payments problems in Java