Problem overview
The cart now has categories. Three parallel arrays describe five products: items (names), prices and categories. The program must add up the prices per category and print one line per category, with the categories sorted alphabetically.
The starting data has apples, bread and bananas in Food, and a shirt and pants in Clothes. The output is:
Clothes: $65
Food: $6
Clothes cost 25 + 40 = 65 and food costs 2 + 3 + 1 = 6. The item names are never printed: only the categories matter in the report.
Approach: accumulate in a map, then sort the keys
The categories aren't known in advance, and the same category appears in several places in the arrays. A map from category to running total is the natural fit: each category is a key, and its value grows as items of that category go by. A first sighting of a category has no entry yet, so the total so far counts as 0.
The program works in two phases. First, one loop over the items fills the map. Second, a loop over the sorted keys builds the output lines. The sorting is a separate step because a map doesn't promise the order you want. The mutableMapOf function in Kotlin does produce a map that remembers the order in which keys were first added, which here would put Food ahead of Clothes, so the alphabetical order has to be asked for explicitly.
This is the same shape as counting words or tallying votes: group by a key, combine the values that share it. The pattern is worth remembering because it turns a problem that looks like it needs nested loops into a single pass.
Step by step
- Create
totals.mutableMapOf<String, Int>()is an empty map from text to integer. - Loop over the positions with
items.indices. The sameiaddresses the same product in all three arrays. - Read the category. Inside the loop,
catiscategories[i]. - Update the category's total. Set
totals[cat]to its current value plusprices[i].getOrDefault(cat, 0)supplies the current value, or 0 the first time. - Create
lines. After the loop, an emptymutableListOf<String>()will hold the output lines. - Sort the keys.
totals.keys.sorted()returns the category names as a new, sorted list. - Loop over the sorted keys. The variable
cattakes each category once, in alphabetical order. - Add one line per category. It is the category,
": $"and its total. - Join the lines into
resultwith newlines between them. - Print
result.
The solution in Kotlin
val items = arrayOf("Apple", "Bread", "Shirt", "Banana", "Pants")
val prices = intArrayOf(2, 3, 25, 1, 40)
val categories = arrayOf("Food", "Food", "Clothes", "Food", "Clothes")
val totals = mutableMapOf<String, Int>()
for (i in items.indices) {
val cat = categories[i]
totals[cat] = totals.getOrDefault(cat, 0) + prices[i]
}
val lines = mutableListOf<String>()
val keys = totals.keys.sorted()
for (cat in keys) {
lines.add(cat + ": $" + totals[cat])
}
val result = lines.joinToString("\n")
println(result)
Kotlin details worth a closer look:
- Assigning with brackets.
totals[cat] = valuecalls the map'ssetoperator: it adds the key when it is new and replaces the value when it exists. Reading the old value first withgetOrDefaultis what makes it an accumulation rather than an overwrite. - Insertion order. With the starting data, printing
totalsdirectly gives{Food=6, Clothes=65}: the keys sit in the order they were first seen. Looping overtotals.keyswithout sorting would therefore print Food first and fail the alphabetical rule. sorted()makes a new list. It sorts the strings in their natural order, which for text means character by character, with uppercase letters before lowercase. The map itself is untouched.- A nullable inside the text.
totals[cat]is anInt?, but the left side of the+is aString, so it is converted to text anyway. Here every key comes from the map's own key set, so the value is nevernull. - Iterating keys, not entries. Looping over the sorted
keysand looking each total up is simple and clear; it costs one lookup per category.
Complexity
Only the sorting depends on the number of categories in a way that is more than linear.
With n items and k distinct categories, the first loop takes O(n) time, because each map update is constant time on average. Sorting the keys takes O(k log k) and building the lines takes O(k). The map and the lists use O(k) extra space.
Edge cases and common mistakes
- Overwriting instead of accumulating. Writing
totals[cat] = prices[i]keeps only the last price of each category. - Skipping the sort. The map's own order is the order of first appearance, not alphabetical.
- Mixing up the arrays. The category comes from
categories[i], not fromitems[i]. - No items. With empty arrays, the map is empty, so
resultis an empty string andprintlnprints an empty line.
Testing
Try two items in two categories: Pen at 4 in Office and Mug at 9 in Home. The map holds {Office=4, Home=9}, and the program prints:
Home: $9
Office: $4
The order of the output follows the sorted names, not the order of the products.
