Drill

ProblemsC++ › payments

Charge each request only once

mediumpaymentsHash mapsArraysSimulationC++

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

C++ 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(std::vector<Event> events) {
    
}

Worked examples

CallResult
applyOnce(std::vector<Event>{Event{std::string("a"), 100}, Event{std::string("b"), 50}, Event{std::string("a"), 100}})150
applyOnce(std::vector<Event>{Event{std::string("a"), 100}, Event{std::string("a"), -100}})100
applyOnce(std::vector<Event>{Event{std::string("x"), 7}})7
applyOnce(std::vector<Event>{})0

Hint

Remember the keys you have already honoured.

Reference solution in C++
int applyOnce(std::vector<Event> events) {
    std::set<string> seen;
    int total = 0;
    for (const auto& e : events) {
        if (!seen.insert(e.key).second) continue;
        total += e.amount;
    }
    return total;
}

The same problem in another language

More payments problems in C++