#2631
Group By
MediumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass through the array and a HashMap (or object) to store the grouped results. This approach is efficient because it reduces the number of lookups and checks needed, leading to a linear time complexity.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty object to hold the grouped results.
- 2Step 2: Loop through each item in the array.
- 3Step 3: For each item, call the provided function to get the key.
- 4Step 4: Use the key to either add the item to an existing array or create a new array.
- 5Step 5: Return the result object.
solution.py6 lines
1def group_by(array, fn):
2 result = {}
3 for item in array:
4 key = fn(item)
5 result.setdefault(key, []).append(item)
6 return resultℹ
Complexity note: The time complexity is O(n) because we loop through the array once, and each key insertion into the object takes average O(1) time. The space complexity is O(n) because in the worst case, we store all items in the result object.
- 1Using a HashMap allows for efficient grouping of items.
- 2Understanding the difference between time complexity in brute force vs optimal solutions is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.