LeetCode Problem Workspace

Allow One Function Call

Learn how to wrap a function so it executes at most once, capturing results while ignoring extra calls efficiently.

category

0

Topics

code_blocks

2

Code langs

hub

0

Related

Practice Focus

Easy · Allow One Function Call core interview pattern

bolt

Answer-first summary

Learn how to wrap a function so it executes at most once, capturing results while ignoring extra calls efficiently.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Allow One Function Call core interview pattern

Try AiBox Copilotarrow_forward

To solve Allow One Function Call, create a wrapper function that tracks whether the original function has been called. On the first invocation, execute and store the result. Subsequent calls return undefined, ensuring the core pattern of single execution is maintained and preventing accidental repeated calls that could cause side effects or incorrect results.

Problem Statement

You are asked to implement a utility that takes an existing function fn and returns a new function that allows fn to be called at most once. The first call should return the original function's output, and all following calls should return undefined.

For example, given fn = (a,b,c) => (a + b + c), invoking the wrapped function with inputs [1,2,3] should return 6, but any later calls such as [2,3,6] should return undefined. This enforces the Allow One Function Call core interview pattern, ensuring predictable function execution.

Examples

Example 1

Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]

Output: [{"calls":1,"value":6}]

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}]

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 array
  • 1 <= calls.length <= 10
  • 1 <= calls[i].length <= 100
  • 2 <= JSON.stringify(calls).length <= 1000

Solution Approach

Use a flag to track execution

Initialize a boolean variable called called as false. When the wrapper function runs, check called; if false, execute fn, store the result, set called to true, and return the result. If called is true, return undefined.

Store result for consistent return

Keep a variable to store the result of the first call. This ensures the first valid call output is preserved for reference or logging, even though subsequent calls return undefined.

Maintain function signature

Use rest parameters in the wrapper to pass any number of arguments to fn. This ensures the wrapper mirrors the original function's signature, keeping the behavior predictable while enforcing single execution.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time and space complexity depend on the function fn and the number of arguments passed. Overhead is minimal, with a single boolean flag and optional result storage, so operations are effectively O(1) per call.

What Interviewers Usually Probe

  • Check if the candidate tracks function execution state correctly.
  • Observe if they handle extra calls without throwing errors.
  • Look for proper argument forwarding and result preservation in the wrapper.

Common Pitfalls or Variants

Common pitfalls

  • Failing to store the result of the first call, causing loss of output for debugging.
  • Not handling additional arguments correctly, breaking the function signature.
  • Allowing multiple executions due to missing or misplaced execution flag.

Follow-up variants

  • Allow multiple calls but limit total executions to a specified count.
  • Reset the single-call state after a timeout, allowing one call per interval.
  • Track the last returned value and always return it instead of undefined for extra calls.

FAQ

What is the main idea behind Allow One Function Call?

The goal is to ensure a function executes only once, returning its result the first time and undefined afterward, enforcing controlled execution.

How do I handle functions with multiple parameters?

Use rest parameters in the wrapper to pass all arguments to the original function while maintaining single-call behavior.

Can I reset the wrapper to allow another call?

By default no; to allow reset, you need to add a method that sets the called flag back to false.

What happens if the first call throws an error?

The error propagates, and subsequent calls are still considered executed unless you catch and handle exceptions within the wrapper.

Why is storing the first call result recommended?

Storing the result preserves output for logging or validation, preventing loss when extra calls return undefined.

terminal

Solution

Solution 1

#### TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * @param {Function} fn
 * @return {Function}
 */
var once = function (fn) {
    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
 */
Allow One Function Call Solution: Allow One Function Call core intervie… | LeetCode #2666 Easy