
Sponsored
Sponsored
This approach involves iterating over each element of the array, applying the provided function to determine the key for each element, and then organizing elements in an object based on these keys.
Time Complexity: O(n * m) where n is the number of elements and m is the average length of strings (due to strcmp operation).
Space Complexity: O(n) for storage of key-value mappings.
1#include <vector>
#include <unordered_map>
#include <string>
std::unordered_map<std::string, std::vector<void*>> groupBy(std::vector<void*> array, std::string (*fn)(void*)) {
std::unordered_map<std::string, std::vector<void*>> grouped;
for (auto& item : array) {
std::string key = fn(item);
grouped[key].emplace_back(item);
}
return grouped;
}This C++ solution leverages std::unordered_map to store the grouping, iterating over each element, and storing values under their respective keys using the function output.
This approach recursively divides the array, processes elements with memoization to store previously encountered keys, thus reducing redundant calculations, which optimizes processing of large arrays.
Time Complexity: O(n * m), where m is affected by recursion depth.
Space Complexity: O(n) for memo storage and call stack.
1def recursive_group(array, fn, memo=None):
2 if memo is None:
3 memo = {}
4 if not array:
5 return memo
6 item = array[0]
7 key = fn(item)
8 if key not in memo:
9 memo[key] = []
10 memo[key].append(item)
11 return recursive_group(array[1:], fn, memo)The Python recursive solution shrinks the list recursively while deploying a dictionary memo that catalogs keys and values in progress.