Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

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:

  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).

:

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.