Final: Shop Stock Keeper
Completed
Keep a shop's stock. Commands: add item qty adds stock; sell item qty sells if there is enough, otherwise prints not enough item and sells nothing; report prints every item that is in stock as item:qty in alphabetical order, separated by spaces (or empty).
Input
Line 1: q. Then q commands.
Output
Messages and reports, one per line.
Example
Input
7 add pen 10 add apple 3 sell pen 4 sell apple 5 report sell apple 3 report
Output
not enough apple apple:3 pen:6 pen:6
Editor
Java
Hints
A TreeMap keeps items in alphabetical order for the report.
Remove an item when its stock reaches 0 so it doesn't appear in the report.
Solution explanation
Every command is O(log n) with a TreeMap; a report is O(n). A HashMap would need sorting on every report.
Show solution
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
TreeMap<String, Integer> stock = new TreeMap<String, Integer>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < q; i++) {
String cmd = sc.next();
if (cmd.equals("add")) {
String item = sc.next();
stock.put(item, stock.getOrDefault(item, 0) + sc.nextInt());
} else if (cmd.equals("sell")) {
String item = sc.next();
int qty = sc.nextInt();
int have = stock.getOrDefault(item, 0);
if (have < qty) {
out.append("not enough ").append(item).append('\n');
} else if (have == qty) {
stock.remove(item);
} else {
stock.put(item, have - qty);
}
} else {
StringBuilder line = new StringBuilder();
for (Map.Entry<String, Integer> e : stock.entrySet()) {
if (line.length() > 0) line.append(' ');
line.append(e.getKey()).append(':').append(e.getValue());
}
out.append(line.length() == 0 ? "empty" : line.toString()).append('\n');
}
}
System.out.print(out);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module