GroupBy for categorization in Kotlin - Time & Space Complexity
When we use groupBy in Kotlin, we want to see how the time it takes changes as the list gets bigger.
We ask: How does grouping items by a key grow with more items?
Analyze the time complexity of the following code snippet.
val items = listOf("apple", "banana", "apricot", "blueberry")
val grouped = items.groupBy { it.first() }
println(grouped)
This code groups a list of words by their first letter.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once for each item (n times).
As the list gets bigger, the time to group grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and groupings |
| 100 | About 100 checks and groupings |
| 1000 | About 1000 checks and groupings |
Pattern observation: The work grows evenly as the list grows.
Time Complexity: O(n)
This means the time to group items grows in a straight line with the number of items.
[X] Wrong: "Grouping takes longer than just looking at each item once because it creates many groups."
[OK] Correct: Grouping just looks at each item once and adds it to a group, so it doesn't multiply the work by the number of groups.
Understanding how grouping scales helps you explain how data categorization works efficiently in real apps.
"What if the grouping key function itself took longer to compute for each item? How would the time complexity change?"
Practice
groupBy function do in Kotlin?Solution
Step 1: Understand the purpose of groupBy
ThegroupByfunction takes a list and groups its elements by a key, returning a map.Step 2: Compare with other functions
Sorting, removing duplicates, and converting to set do different things than grouping by a key.Final Answer:
It organizes a list into a map based on a key selector function. -> Option BQuick Check:
groupBy = organize by key [OK]
- Confusing groupBy with sorting functions
- Thinking groupBy removes duplicates
- Mixing groupBy with set conversion
Solution
Step 1: Review Kotlin lambda syntax
Kotlin uses curly braces withitfor single-parameter lambdas:{ it.first() }.Step 2: Check each option
val result = list.groupBy { it.first() } uses correct Kotlin syntax. val result = list.groupBy(it -> it.first()) uses arrow syntax which is invalid here. val result = list.groupBy { it.first } omits parentheses on first() method call, causing compile error. val result = list.groupBy { first(it) } calls undefined functionfirst().Final Answer:
val result = list.groupBy { it.first() } -> Option AQuick Check:
Use curly braces and it.first() [OK]
- Using arrow syntax inside groupBy lambda
- Calling undefined functions like first(it)
- Omitting parentheses on first() method call
val numbers = listOf(1, 2, 3, 4, 5, 6)
val grouped = numbers.groupBy { if (it % 2 == 0) "even" else "odd" }
println(grouped)Solution
Step 1: Understand the grouping condition
The lambda groups numbers by "even" if divisible by 2, else "odd".Step 2: Group numbers accordingly
Numbers 2,4,6 go to "even"; 1,3,5 go to "odd".Final Answer:
{odd=[1, 3, 5], even=[2, 4, 6]} -> Option AQuick Check:
Group by even/odd labels [OK]
- Confusing keys with values in output
- Expecting boolean keys instead of strings
- Thinking groupBy sorts the list
val words = listOf("apple", "banana", "apricot")
val grouped = words.groupBy { it[0] }
println(grouped)Solution
Step 1: Check indexing on strings
In Kotlin, strings support indexing with[0]to get first character.Step 2: Validate groupBy usage
The lambda{ it[0] }is valid and groups words by their first character.Final Answer:
No error; code runs and groups by first character -> Option DQuick Check:
Strings support indexing; groupBy accepts lambdas [OK]
- Thinking indexing strings causes error
- Believing groupBy needs named functions only
- Assuming characters must be converted to strings
Pair<String, Int> where the first element is the name and the second is the age, how would you group them by age category "minor" (age < 18) or "adult" (age >= 18) using groupBy?Solution
Step 1: Identify grouping key based on age
We want to group by "minor" if age < 18, else "adult".Step 2: Use groupBy with conditional key
Access age withit.secondand apply if-else to return category string.Final Answer:
people.groupBy { if (it.second < 18) "minor" else "adult" } -> Option CQuick Check:
Group by age category using conditional [OK]
- Grouping by name or name length instead of age
- Grouping by exact age instead of categories
- Confusing first and second in Pair
Ready to prove it?
Pass the test and this pattern moves unknown
