LeetCode 2631: Group By Solution
Master LeetCode problem 2631 (Group By), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2631. Group By
Problem Explanation
Explanation:
To implement the groupBy method on an array, we can iterate over the array, apply the provided fn function to each element to get the key, and then group the elements based on these keys. We can use a HashMap (or dictionary in Python) to store the grouped elements. If an element with the same key already exists in the map, we append the current element to the list of values corresponding to that key.
- Time complexity: O(n), where n is the number of elements in the input array.
- Space complexity: O(n) to store the grouped elements in the map.
:
Solution Code
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ArrayGroupBy {
public static Map<String, List<Object>> groupBy(Object[] array, Function<Object, String> fn) {
Map<String, List<Object>> groupedMap = new HashMap<>();
for (Object item : array) {
String key = fn.apply(item);
groupedMap.putIfAbsent(key, new ArrayList<>());
groupedMap.get(key).add(item);
}
return groupedMap;
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2631 (Group By)?
This page provides optimized solutions for LeetCode problem 2631 (Group By) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2631 (Group By)?
The time complexity for LeetCode 2631 (Group By) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2631 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2631 in Java, C++, or Python.