Refund ledger audit
A shop keeps order totals and a chronological list of refund requests, all in whole cents. Accept a refund only when its order exists and the cumulative accepted refunds will not exceed that order's total. Rejected requests do not change balances. After processing every request, print each order's remaining balance sorted by order ID, then the number of rejected requests.
Input
First line N, then N lines order_id total_cents. Next line M, then M lines order_id refund_cents.
Output
One line per order: order_id remaining_cents, sorted by ID. Final line: rejected X.
Example 1
Input
2 a1 1000 b2 500 4 a1 300 x9 100 a1 800 b2 500
Output
a1 700 b2 0 rejected 2
The unknown x9 request and the 800-cent over-refund are rejected; b2 is exactly refunded.
Constraints
- 1 <= N <= 100; order IDs are unique lowercase letters and digits
- 0 <= M <= 300
- 1 <= total_cents, refund_cents <= 1000000
- Process requests in input order; do not use floating-point money
Hints
Hint 1 of 3
Store the remaining balance of each order in a Map.
Hint 2 of 3
Check has(id) before reading the balance; zero is a valid remaining amount.
Hint 3 of 3
Only subtract after both checks pass, and sort IDs at reporting time.
Solution
Show a reference solution and explanation
const count = Number(readline());
const remaining = new Map();
for (let i = 0; i < count; i++) {
const [id, total] = readline().split(' ');
remaining.set(id, Number(total));
}
const refunds = Number(readline());
let rejected = 0;
for (let i = 0; i < refunds; i++) {
const [id, amountText] = readline().split(' ');
const amount = Number(amountText);
if (!remaining.has(id) || amount > remaining.get(id)) {
rejected++;
} else {
remaining.set(id, remaining.get(id) - amount);
}
}
for (const id of [...remaining.keys()].sort()) console.log(id, remaining.get(id));
console.log('rejected', rejected);
Why it works
The Map is the ledger's current state. Each refund is validated against that state in arrival order, so two individually affordable refunds cannot together exceed the order total. An unknown ID or excessive amount increments the rejected counter without mutating any balance. Integer cents avoid floating-point rounding in money calculations. Sorting only for output makes the report deterministic.
Lesson for this exercise: JavaScript Objects: Properties, Methods and Nesting