Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.
fn.undefined.
Example 1:
Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
Output: [{"calls":1,"value":6}]
Explanation:
const onceFn = once(fn);
onceFn(1, 2, 3); // 6
onceFn(2, 3, 6); // undefined, fn was not called
Example 2:
Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
Output: [{"calls":1,"value":140}]
Explanation:
const onceFn = once(fn);
onceFn(5, 7, 4); // 140
onceFn(2, 3, 6); // undefined, fn was not called
onceFn(4, 6, 8); // undefined, fn was not called
Constraints:
calls is a valid JSON array1 <= calls.length <= 101 <= calls[i].length <= 1002 <= JSON.stringify(calls).length <= 1000This approach leverages closures to keep track of whether the original function has been called. A closure allows the function to maintain state across calls, which in this case is whether the function should execute or return undefined.
This JavaScript solution defines a function once that takes a function fn as an argument. It uses a flag called to check if the function has been executed before. The first call executes fn and stores the result. Subsequent calls return undefined.
Python
Java
Time Complexity: O(1) for each call, Space Complexity: O(1), as no additional data structures are used.
In this approach, use an external flag variable to keep track of whether the function has already been executed. This approach is more language-specific where closure support is limited.
This C solution demonstrates using a structure to maintain state. The Once struct includes a function pointer and a flag called which checks for the first invocation. once_call executes only on the first call, thereafter returns an undefined equivalent.
C++
Time Complexity: O(1) per call, Space Complexity: O(1) for state flag.
| Approach | Complexity |
|---|---|
| Use a Closure to Track Calls | Time Complexity: O(1) for each call, Space Complexity: O(1), as no additional data structures are used. |
| Flag with External State | Time Complexity: O(1) per call, Space Complexity: O(1) for state flag. |
Allow One Function Call - Leetcode 2666 - JavaScript 30-Day Challenge • NeetCodeIO • 11,009 views views
Watch 9 more video solutions →Practice Allow One Function Call with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor