45. Inventory Frequency Counter
Difficulty: easy · String, Hashing
Problem
A shop records the items it sold as a single line of item names separated by spaces. Count how many times each item appears. If the line contains any digit (`0`-`9`) anywhere, the record is corrupt: print `Invalid input` and nothing else. Otherwise, print one line per distinct item, in the order each item **first** appears, in the form `item: count`. Item names are case-sensitive.
Input
A single line of item names separated by single spaces.
Output
Print `Invalid input`, or one `item: count` line per distinct item in order of first appearance.
Example 1
Input: apple banana apple cherry banana apple Output: apple: 3 banana: 2 cherry: 1
Explanation: apple appears 3 times, banana twice and cherry once, listed in order of first appearance.
Example 2
Input: pen pencil2 eraser Output: Invalid input
Explanation: 'pencil2' contains a digit, so the record is invalid.
Example 3
Input: Pen pen PEN pen Output: Pen: 1 pen: 2 PEN: 1
Explanation: Names are case-sensitive: Pen 1, pen 2, PEN 1.
Constraints
- 1 <= number of items <= 10^5 - 1 <= length of each item <= 20 - Items consist of English letters, possibly with digits (which make the input invalid)
Solutions are judged against 3 sample and 9 hidden tests. Sign in to solve it · All problems