2666. Allow One Function Call
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
called
initialized tofalse
to track iffn
has been called. - Create a new function
onceFn
that takes the same arguments asfn
. - Inside
onceFn
, check ifcalled
isfalse
.- If
called
isfalse
, callfn
with the provided arguments and store the result.- Set
called
totrue
. - Return the result of calling
fn
.
- Set
- If
called
istrue
, returnundefined
.
- If
Time complexity: O(1) for each function call. Space complexity: O(1).
:
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;
}
};
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.