NeetCode #953LC-2632MediumJavaScript
← Back to All Problems#953 · #2632 · Curry(柯里化)
📌 Problem Statement & Constraints
Given a function
fn, return its curried version: it may be called with one argument at a time or several at once, and it executes fn only once the accumulated argument count reaches fn.length.💡 Core Algorithmic Approaches
fn.lengthgives the number of declared parameters, which is the threshold for execution.- Collect arguments recursively: each call concatenates the new arguments with the ones already gathered.
- When the accumulated count is at least
fn.length, invokefn(...args)and return the result. - Otherwise return a function that keeps accepting arguments, preserving the currying behaviour.
💻 Benchmark Python3 Implementation
var curry = function(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args); // enough arguments -> invoke
}
return (...next) => curried(...args, ...next); // keep collecting
};
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1) per call, excluding the final fn invocation.
💾 Space Complexity
O(k): the accumulated argument array.
⚠️ Interview Pitfalls & Follow-ups
- Hard-coding the parameter count: currying must key off the original function's
fn.length. - Only supporting one argument per call:
curried(1, 2)must be able to accumulate several at once. - Executing
fnwhile arguments are still short: the result would beundefinedinstead of a waiting function. - Relying on the
argumentsobject: it is not bound inside arrow functions; rest parameters are the correct tool.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.