LeetCode Problem Workspace
Group By
Implementing the Group By core interview pattern efficiently sorts array elements into keyed groups based on a selector function.
0
Topics
1
Code langs
0
Related
Practice Focus
Medium · Group By core interview pattern
Answer-first summary
Implementing the Group By core interview pattern efficiently sorts array elements into keyed groups based on a selector function.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Group By core interview pattern
This problem requires extending arrays with a groupBy method that returns an object keyed by a selector function. Each key maps to an array of all original items producing that key. The challenge focuses on correctly aggregating items without overwriting keys and handling any input type consistently.
Problem Statement
Design a method array.groupBy(fn) that groups elements of any array based on a callback function fn. The callback returns a string key for each element, and the method returns an object where each key maps to all elements producing that key.
Ensure your solution handles empty arrays, arrays of objects or primitives, and any valid fn output string. The function must maintain all items in their original form and group them correctly without loss or duplication.
Examples
Example 1
Input: array = [ {"id":"1"}, {"id":"1"}, {"id":"2"} ], fn = function (item) { return item.id; }
Output: { "1": [{"id": "1"}, {"id": "1"}], "2": [{"id": "2"}] }
Output is from array.groupBy(fn). The selector function gets the "id" out of each item in the array. There are two objects with an "id" of 1. Both of those objects are put in the first array. There is one object with an "id" of 2. That object is put in the second array.
Example 2
Input: array = [ [1, 2, 3], [1, 3, 5], [1, 5, 9] ] fn = function (list) { return String(list[0]); }
Output: { "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] }
The array can be of any type. In this case, the selector function defines the key as being the first element in the array. All the arrays have 1 as their first element so they are grouped together. { "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] }
Example 3
Input: array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] fn = function (n) { return String(n > 5); }
Output: { "true": [6, 7, 8, 9, 10], "false": [1, 2, 3, 4, 5] }
The selector function splits the array by whether each number is greater than 5.
Constraints
- 0 <= array.length <= 105
- fn returns a string
Solution Approach
Initialize the grouping object
Start by declaring an empty object to store the grouped results. Iterate over each array element, apply the selector function fn, and check if the key exists. If not, create a new array for that key.
Populate the groups
Push each item into the corresponding array for its key. This ensures all elements producing the same key are aggregated. Avoid overwriting existing arrays to preserve previous elements.
Return the grouped object
After processing all elements, return the object containing all keys mapped to their respective arrays. This final step completes the Group By pattern and provides the expected output structure.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity is O(n) because each element is visited once to compute its key. Space complexity is O(n) as a new object stores references to all original elements grouped by their keys.
What Interviewers Usually Probe
- Ask candidate to explain how keys are generated and handled if duplicates occur.
- Check if candidate preserves the original element references in the grouped arrays.
- Probe edge cases like empty arrays or unusual fn outputs to verify robust handling.
Common Pitfalls or Variants
Common pitfalls
- Overwriting arrays for duplicate keys instead of appending elements.
- Returning a modified input array rather than a new grouped object.
- Not converting keys to strings consistently when fn returns non-string values.
Follow-up variants
- Group elements by multiple keys by allowing fn to return an array of keys for each item.
- Implement a stable Group By where insertion order of items is preserved in each array.
- Create a version that groups asynchronously if fn involves async computation.
FAQ
What is the main idea behind the Group By problem?
The core idea is to transform an array into an object where each key is produced by a selector function and maps to all items generating that key.
Can array elements be of different types?
Yes, elements can be objects, arrays, or primitives. The selector function fn determines the key, so all types are supported as long as fn returns a string.
How does GhostInterview prevent common mistakes in Group By?
It flags overwriting arrays, ensures all elements are included, and checks that keys are consistently handled as strings.
What happens if the input array is empty?
The groupBy method returns an empty object, correctly handling the edge case without errors.
Is maintaining element order important in Group By?
Yes, each group array should maintain the order elements appeared in the original array for consistency and predictable results.
Solution
Solution 1
#### TypeScript
declare global {
interface Array<T> {
groupBy(fn: (item: T) => string): Record<string, T[]>;
}
}
Array.prototype.groupBy = function (fn) {
return this.reduce((acc, item) => {
const key = fn(item);
if (acc[key]) {
acc[key].push(item);
} else {
acc[key] = [item];
}
return acc;
}, {});
};
/**
* [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
*/