
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.
1using System.Collections.Generic;
public class GroupBy {
public static Dictionary<string, List<T>> GroupBy<T>(List<T> list, Func<T, string> fn) {
var grouped = new Dictionary<string, List<T>>();
foreach (var item in list) {
var key = fn(item);
if (!grouped.ContainsKey(key)) {
grouped[key] = new List<T>();
}
grouped[key].Add(item);
}
return grouped;
}
}The C# solution uses a dictionary to correlate function results with value lists. Elements are grouped during iteration and include generic types for flexibility.
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.
1import java.util.*;
2
3public class RecursiveGroupBy {
4 public static Map<String, List<Object>> recursiveGroup(List<Object> list, Function<Object, String> fn, Map<String, List<Object>> memo) {
5 if (list.isEmpty()) return memo;
6 Object obj = list.remove(0);
7 String key = fn.apply(obj);
8 memo.computeIfAbsent(key, k -> new ArrayList<>()).add(obj);
9 return recursiveGroup(list, fn, memo);
10 }
11}Java's version of recursive grouping relies on passing a list and a hashmap (memo) through layers of recursion. By destructuring the list into subproblems, it builds results while retaining intermediate state in the memoization structure.