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

Easy

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:

  1. Create a boolean variable called initialized to false to track if fn has been called.
  2. Create a new function onceFn that takes the same arguments as fn.
  3. Inside onceFn, check if called is false.
    • If called is false, call fn with the provided arguments and store the result.
      • Set called to true.
      • Return the result of calling fn.
    • If called is true, return undefined.

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.

Back to LeetCode Solutions