Allow One Function Call solution and explanation
9 more videos on this problem
Allow One Function Call - Leetcode 2666 - JavaScript 30-Day ChallengeNeetCodeIO · 10:15 · 12K views
Leetcode Javascript Day-8 challenge - ` 2666. Allow One Function Call`.AnshulOnTech · 5:49 · 1K views
2666. Allow One Function Call - Leetcode JavaScript Solution with ExplanationEndeavour Monk · 4:46 · 980 views
#Day10 |2666. Allow One Function Call | 30 Days of Javascript | Leetcode-2666 | 30 Days ChallengeCoding with Ankita · 11:22 · 584 views
30 days of JavaScript - Allow One Function CallCode With Bertrand · 15:55 · 169 views
Allow One Function Call - LeetCode 2666 - JavaScript - JS 30 Day Challenge Day 8Alpha-Code · 8:25 · 141 views
Day 8 - 30 Days LeetCode JavaScript Challenge: 2666. Allow One Function CallvanAmsen · 6:08 · 135 views
2666. Allow One Function Call - Day 8/30 Leetcode Javascript ChallengeProgramming Live with Larry · 5:15 · 133 views
Javascript | Leetcode 2666 - Allow One Function Call - Kanika VatsKanika Vats · 4:56 · 74 views
2666. Allow One Function Call | Day 10 – Build a "once" Function in JavaScriptCodeCrafting with Vishnu · 9:41 · 40 views
The problem
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.
- The first time the returned function is called, it should return the same result as
fn. - Every subsequent time it is called, it should return
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:
callsis a valid JSON array1 <= calls.length <= 101 <= calls[i].length <= 1002 <= JSON.stringify(calls).length <= 1000
Approach overview
Problem Overview: You need to wrap an existing function so it can be executed only once. The first call runs the original function and returns its result. Every later call must return undefined without executing the function again.
This is a classic function wrapper problem. The wrapper keeps track of whether the underlying function has already been executed. Once the first invocation happens, all later calls are ignored. The challenge is managing that state efficiently while preserving the original function's arguments.
Approach 1: Use a Closure to Track Calls (O(1) time, O(1) space)
The most common solution uses a closure that stores whether the function has already been executed. Create a boolean variable such as called inside the outer function. The returned inner function checks this flag before executing the original function. If called is false, invoke the function using the provided arguments and update the flag to true. If it is already true, simply return undefined.
This works because closures preserve access to variables from their enclosing scope even after the outer function returns. Each wrapped function instance gets its own independent state. The runtime cost is constant since each invocation performs only a flag check and possibly a single function call. This pattern is widely used in closures, higher-order functions, and JavaScript-style functional utilities.
Approach 2: Flag with External State (O(1) time, O(1) space)
Languages like C or C++ do not have built-in closures in the same way as JavaScript or Python. Instead, store the execution state in a variable outside the wrapper function or inside a small struct/object. The wrapper checks this shared flag before executing the original function pointer.
The logic is identical to the closure approach: check the flag, execute the function once, then permanently flip the flag. The difference is how the state is stored and passed around. This method appears in lower-level languages where function wrappers rely on explicit state management instead of lexical scope. It still runs in constant time with constant memory usage.
Problems like this appear frequently in API design and functional utilities where you want a side-effect to occur only once. Examples include initializing configuration, running startup logic, or protecting expensive operations.
Recommended for interviews: The closure-based approach is the expected answer in JavaScript, Python, and Java interviews. It demonstrates understanding of lexical scope, higher-order functions, and state captured inside a wrapper. Mentioning the external state approach shows awareness of how the same design works in languages without native closures. Both solutions run in O(1) time and O(1) space, but the closure version is cleaner and idiomatic for modern function design problems.
Approach 1: Use a Closure to Track Calls
This 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.
def once(fn):
called = False
result = None
def inner(*args):
nonlocal called, result
if not called:
called = True
result = fn(*args)
return result
return None
return innerimport java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
public class Once {
public static <T, R> Function<T, R> once(Function<T, R> fn) {
AtomicBoolean called = new AtomicBoolean(false);
return (T arg) -> {
if (called.compareAndSet(false, true)) {
return fn.apply(arg);
}
return null;
};
}
}function once(fn) {
let called = false;
let result;
return function(...args) {
if (!called) {
called = true;
result = fn(...args);
return result;
}
return undefined;
};
}This Python solution utilizes an inner function with nonlocal keyword to maintain the state of called and result. On first call, the result is computed and stored, while subsequent calls return None.
Time Complexity: O(1) per call, Space Complexity: O(1).
Approach 2: Flag with External State
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.
#include <iostream>
#include <functional>
class Once {
public:
Once(std::function<int(int, int, int)> fn) : fn(fn), called(false) {}
int operator()(int a, int b, int c) {
if (!called) {
called = true;
result = fn(a, b, c);
return result;
}
return -1; // Undefined equivalent
}
private:
std::function<int(int, int, int)> fn;
bool called;
int result;
};
int main() {
Once onceFn([](int a, int b, int c){ return a + b + c; });
std::cout << onceFn(1, 2, 3) << std::endl; // Outputs the result
std::cout << onceFn(2, 3, 4) << std::endl; // Outputs undefined equivalent
return 0;
}#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
typedef int (*Function)(int, int, int);
typedef struct {
Function fn;
bool called;
int result;
} Once;
Once* once(Function fn) {
Once* o = (Once*)malloc(sizeof(Once));
o->fn = fn;
o->called = false;
o->result = 0;
return o;
}
int once_call(Once* o, int a, int b, int c) {
if (!o->called) {
o->called = true;
o->result = o->fn(a, b, c);
return o->result;
}
return -1; // Represent undefined
}
int sum(int a, int b, int c) {
return a + b + c;
}
int main() {
Once* onceFn = once(sum);
printf("%d\n", once_call(onceFn, 1, 2, 3)); // Output the sum
printf("%d\n", once_call(onceFn, 2, 3, 6)); // Output undefined equivalent
free(onceFn);
return 0;
}This C++ solution uses a class to manage the function call state. The class Once stores a flag called to track whether the function has been executed, ensuring it runs only once and returns an undefined equivalent on further calls.
Time Complexity: O(1) per call, Space Complexity: O(1) due to single boolean state.
Approach 3: Default Approach
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type OnceFn = (...args: JSONValue[]) => JSONValue | undefined;
function once(fn: Function): OnceFn {
let called = false;
return function (...args) {
if (!called) {
called = true;
return fn(...args);
}
};
}
/**
* let fn = (a,b,c) => (a + b + c)
* let onceFn = once(fn)
*
* onceFn(1,2,3); // 6
* onceFn(2,3,6); // returns undefined without calling fn
*/Complexity comparison
| Approach | Complexity |
|---|---|
| Use a Closure to Track Calls | Time Complexity: O(1) per call, Space Complexity: O(1). |
| Flag with External State | Time Complexity: O(1) per call, Space Complexity: O(1) due to single boolean state. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Closure to Track Calls | O(1) per call | O(1) | Best choice in JavaScript, Python, and Java where closures or lambdas can capture state |
| External State Flag | O(1) per call | O(1) | Useful in C/C++ or low-level implementations where closures are not available |
Frequently asked questions
Is Allow One Function Call easy or hard?
Allow One Function Call is classified as an Easy problem. The main concept is understanding closures or maintaining persistent state across function calls. Once you recognize that a single boolean flag is enough to control execution, the implementation becomes straightforward.
Allow One Function Call Python/Java solution
In Python or Java, create a wrapper function that stores a boolean variable indicating whether the function has already executed. The wrapper checks this variable before calling the original function. After the first execution, the variable is updated so later calls return undefined or the equivalent null behavior.
How to solve Allow One Function Call in O(1)?
Store a boolean variable such as `called` inside a closure. When the returned function runs, check the flag. If it is false, execute the original function with the provided arguments and set the flag to true. If it is already true, return undefined immediately. This guarantees constant time per call.
What is the best approach for Allow One Function Call?
The best approach uses a closure with a boolean flag that records whether the function has already been executed. The wrapper checks the flag, calls the original function once, and flips the flag to prevent future execution. This runs in O(1) time per call and uses O(1) extra space.
Is Allow One Function Call asked at Google/Amazon/Meta?
The exact problem may not always appear verbatim, but the concept is common in interviews. Variations involving function wrappers, memoization, and higher-order utilities frequently appear at companies like Google, Amazon, and Meta during JavaScript or system design style coding rounds.
What data structure is used in Allow One Function Call?
The problem does not require a complex data structure. It relies on a simple boolean flag stored in a closure or external variable. The key concept is state persistence across function calls rather than arrays, hash maps, or trees.
What is the time complexity of Allow One Function Call?
Each invocation performs a simple boolean check and possibly one function execution. That makes the time complexity O(1) per call. The wrapper also stores only a single flag variable, so the space complexity is O(1).
