NeetCode #967LC-2631MediumJavaScript
← Back to All Problems#967 · #2631 · Group By(分组)
📌 Problem Statement & Constraints
Implement
Array.prototype.groupBy(fn): group the elements by the value returned by fn(element) and return a plain object whose keys are the (stringified) group results and whose values are arrays of the grouped elements.💡 Core Algorithmic Approaches
- Extend
Array.prototypewith thegroupBymethod. - Iterate
this, computek = fn(x), and appendxtores[k]. - Use logical-or assignment
res[k] ||= []to create the bucket on first encounter. - Do not use an arrow function, since
thismust refer to the calling array.
💻 Benchmark Python3 Implementation
Array.prototype.groupBy = function(fn) {
const res = {};
for (const x of this) {
const k = fn(x);
(res[k] ||= []).push(x); // create the bucket on first encounter
}
return res;
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass over the array.
💾 Space Complexity
O(n): the result object.
⚠️ Interview Pitfalls & Follow-ups
- Defining the method with an arrow function:
thiswould be lost. - Forgetting to initialise
res[k]: that throws onundefined.push. - Expecting non-string keys to stay distinct: object keys are coerced to strings, so
1and a string1merge into one bucket. - Returning a
Map: the problem requires a plain object.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.