LeetCode 2666: Allow One Function Call Solution
Master LeetCode problem 2666 (Allow One Function Call), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2666. Allow One Function Call
Problem Explanation
Explanation:
To solve this problem, we need to create a new function that wraps the original function fn. This new function should ensure that fn is called at most once. We can achieve this by keeping track of whether fn has been called before. If it has been called, we return undefined. Otherwise, we call fn and record the result.
Here is the algorithm:
- Create a boolean variable
calledinitialized tofalseto track iffnhas been called. - Create a new function
onceFnthat takes the same arguments asfn. - Inside
onceFn, check ifcalledisfalse.- If
calledisfalse, callfnwith the provided arguments and store the result.- Set
calledtotrue. - Return the result of calling
fn.
- Set
- If
calledistrue, returnundefined.
- If
Time complexity: O(1) for each function call. Space complexity: O(1).
:
Solution Code
import java.util.*;
import java.util.function.Function;
class Solution {
public static Function<int[], Integer> once(Function<int[], Integer> fn) {
boolean called = false;
int result = 0;
return (args) -> {
if (!called) {
result = fn.apply(args);
called = true;
return result;
} else {
return null;
}
};
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2666 (Allow One Function Call)?
This page provides optimized solutions for LeetCode problem 2666 (Allow One Function Call) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2666 (Allow One Function Call)?
The time complexity for LeetCode 2666 (Allow One Function Call) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2666 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2666 in Java, C++, or Python.