#2666
Allow One Function Call
EasyClosureFunction Decorators
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(1) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal solution is similar to the brute-force approach but emphasizes clarity and efficiency. We maintain a single flag to track if the function has been called, ensuring we only check this once.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a flag to track if the function has been called.
- 2Step 2: Define the wrapper function that checks the flag.
- 3Step 3: If the function has not been called, invoke the original function and set the flag; otherwise, return undefined.
solution.py9 lines
1def once(fn):
2 called = False
3 def wrapper(*args):
4 nonlocal called
5 if not called:
6 called = True
7 return fn(*args)
8 return None
9 return wrapperℹ
Complexity note: The time complexity remains O(1) as we only check a flag and call the function once. The space complexity is O(1) since we use a constant amount of space.
- 1The function should only execute once, so tracking the state is crucial.
- 2Using closures allows us to maintain state without exposing it outside the function.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.