Problem Description
Enhance all arrays so that you can call array.groupBy(fn) on any array. The method should take a function that returns a string key for each item in the array, and then return an object where keys are the results of the function and values are arrays containing all items from the original array that correspond to that key. The order of items in each group should be preserved.
Key Insights
- Extend the Array prototype (or add a utility function) to include a groupBy method.
- Iterate through the array only once to maintain O(n) time complexity.
- Use an object (hash map) where keys are the output of the provided function and values are arrays.
- Ensure that items are appended in order to maintain the input order within each group.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n), as we store all elements in the resulting grouped object.
Solution
We use an iterative approach that goes through each element in the array exactly once. For each element, we compute its key by calling the provided function. If the key is already present in the group object, we append the element to the existing array. Otherwise, we create a new array for that key with the current element.
For Python and JavaScript, we can modify the behavior by creating a utility function or extending a class. For Java and C++, we provide separate implementations that mimic similar behavior by using collections like HashMap or unordered_map.