Problem
Given a function fn
, return a curried version of that function.
A curried function is a function that accepts fewer or an equal number of parameters as the original function and returns either another curried function or the same value the original function would have returned.
In practical terms, if you called the original function like sum(1,2,3)
, you would call the curried version like csum(1)(2)(3), ``csum(1)(2,3)
,
csum(1,2)(3)
, or csum(1,2,3)
. All these methods of calling the curried function should return the same value as the original.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Constraints:
1 <= inputs.length <= 1000
0 <= inputs[i][j] <= 10^5
0 <= fn.length <= 1000
inputs.flat().length == fn.length
- function parameters explicitly defined
- If
fn.length > 0
then the last array ininputs
is not empty - If
fn.length === 0
theninputs.length === 1
Solution
Method 1 – Closure with Argument Accumulation
Intuition
The key idea is to use a closure to accumulate arguments until the original function’s arity is satisfied, then call the original function. Each call to the curried function collects more arguments, and when enough arguments are collected, the original function is invoked.
Approach
- Define a function
curry
that takes a functionfn
. - Inside, define a helper function that accumulates arguments.
- If the number of accumulated arguments is at least
fn.length
, callfn
with those arguments. - Otherwise, return a new function that collects more arguments.
- The closure ensures arguments are preserved across calls.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
per call, as each call just accumulates arguments or calls the original function. - 🧺 Space complexity:
O(n)
, where n is the number of arguments accumulated (at most fn.length).