MediumObjectsNot started

Warehouse movement tally

A warehouse records movements as item name and signed quantity. Read every movement, total quantities per item, and print items alphabetically as name total, including a final total of zero.

Input

First line N. Next N lines: a lowercase item name and signed integer quantity.

Output

One line per item in alphabetical order: name, one space, final total.

Example 1

Input

5
bolts 8
nuts 4
bolts -3
washers 2
nuts -4

Output

bolts 5
nuts 0
washers 2

Repeated item movements are accumulated before the keys are sorted.

Constraints

  • 1 <= N <= 200
  • -1000 <= quantity <= 1000

Hints

Hint 1 of 3

Use item names as object keys.

Hint 2 of 3

The nullish-coalescing expression totals[name] ?? 0 supplies a starting zero.

Hint 3 of 3

Sort Object.keys(totals) before printing.

Solution

Show a reference solution and explanation
 JavaScript · reference solution
const count = Number(readline());
const totals = {};
for (let i = 0; i < count; i++) {
  const [name, amount] = readline().split(' ');
  totals[name] = (totals[name] ?? 0) + Number(amount);
}
for (const name of Object.keys(totals).sort()) console.log(name, totals[name]);

Why it works

The object stores one running total per name. A missing key falls back to zero, and sorting only at the reporting step separates data collection from presentation.

Lesson for this exercise: JavaScript Objects: Properties, Methods and Nesting

Your program
const count = Number(readline());
const totals = {};
for (let i = 0; i < count; i++) {
  const [name, amount] = readline().split(' ');
  // update totals
}
for (const name of Object.keys(totals).sort()) console.log(name, totals[name]);

Tests: 3 cases including the examples. Passing every test marks the exercise solved in this browser.

Ready for a challenge?

How this page was checked. Every program on it was run with Node.js 22 at build time; runs in your browser in an isolated Web Worker by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.