2666. Allow One Function Call LeetCode Solution

In this guide, you will get 2666. Allow One Function Call LeetCode Solution with the best time and space complexity. The solution to Allow One Function Call problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Allow One Function Call solution in C++
  4. Allow One Function Call solution in Java
  5. Allow One Function Call solution in Python
  6. Additional Resources
2666. Allow One Function Call LeetCode Solution image

Problem Statement of Allow One Function Call

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:

calls is a valid JSON array
1 <= calls.length <= 10
1 <= calls[i].length <= 100
2 <= JSON.stringify(calls).length <= 1000

Complexity Analysis

  • Time Complexity: Google AdSense
  • Space Complexity: Google Analytics
See also  1005. Maximize Sum Of Array After K Negations LeetCode Solution

2666. Allow One Function Call LeetCode Solution in C++

type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type OnceFn = (...args: JSONValue[]) => JSONValue | undefined;

function once(fn: Function): OnceFn {
  let isCalled = false;
  return function (...args) {
    if (isCalled) {
      return;
    }
    isCalled = true;
    return fn(...args);
  };
}
/* code provided by PROGIEZ */

2666. Allow One Function Call LeetCode Solution in Java

N/A
// code provided by PROGIEZ

2666. Allow One Function Call LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.