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

  1. Use a closure boolean flag called to record whether fn has run.
  2. On the first call set the flag to true, then invoke fn(...args) and return its result.
  3. On later calls return early with undefined (a function with no return value already yields undefined).
  4. 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 null instead of undefined after the first call: the problem specifies undefined.
  • Setting the flag after invoking fn: if fn throws, the flag would remain false and a retry would be allowed.