NeetCode #951LC-2666EasyJavaScript
← Back to All Problems#951 · #2666 · Allow One Function Call(只允许一次函数调用)
📌 Problem Statement & Constraints
Given a function
fn, return a wrapper that executes fn and returns its result on the first call, and returns undefined on every subsequent call without executing fn again.💡 Core Algorithmic Approaches
- Use a closure boolean flag
calledto record whetherfnhas run. - On the first call set the flag to true, then invoke
fn(...args)and return its result. - On later calls return early with
undefined(a function with no return value already yieldsundefined). - Arguments and the return value of the original function must be forwarded faithfully.
💻 Benchmark Python3 Implementation
var once = function(fn) {
let called = false; // closure flag
return function(...args) {
if (called) return undefined; // subsequent calls short-circuit
called = true;
return fn(...args); // first call forwards args and result
};
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1): constant time per call, excluding fn itself.
💾 Space Complexity
O(1): a single boolean flag.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting to spread the arguments:
fn(...args)is required to forward every parameter. - Returning
nullinstead ofundefinedafter the first call: the problem specifiesundefined. - Setting the flag after invoking
fn: iffnthrows, the flag would remain false and a retry would be allowed.