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

public int ApplyOnce(List<Event> events) {
    
}

Worked examples

CallResult
ApplyOnce(new List<Event> { new Event("a", 100), new Event("b", 50), new Event("a", 100) })150
ApplyOnce(new List<Event> { new Event("a", 100), new Event("a", -100) })100
ApplyOnce(new List<Event> { new Event("x", 7) })7
ApplyOnce(new List<Event> { })0

Hint

Remember the keys you have already honoured.

Reference solution in C#
public int ApplyOnce(List<Event> events) {
    var seen = new HashSet<string>();
    int total = 0;
    foreach (var e in events) {
        if (!seen.Add(e.Key)) continue;
        total += e.Amount;
    }
    return total;
}

The same problem in another language

More payments problems in C#