LeetCode 2693: Call Function with Custom Context

Problem Description

Explanation

To implement the callPolyfill method, we need to create a function that takes an object obj as its first parameter and any number of additional arguments. This object obj will become the this context for the function, and the additional arguments will be passed to the function. We will achieve this by creating a higher-order function that returns a new function with the desired behavior. The new function will use the object obj as its this context and call the original function with the provided arguments.

Algorithmic Idea

  1. Create a higher-order function callPolyfill that takes the original function fn as input.
  2. Return a new function that:
    • Accepts the object obj and additional arguments args.
    • Binds the object obj as the this context using the apply method.
    • Calls the original function fn with the bound this context and the additional arguments.

Time Complexity

The time complexity of this solution is O(1) as it directly calls the original function with the provided arguments.

Space Complexity

The space complexity of this solution is O(1) as it does not use any extra space proportional to the input size.

Solutions

import java.util.function.Function;

class Solution {
    public static Function<Object, Object> callPolyfill(Function<Object, Object> fn) {
        return obj -> {
            Object[] args = (Object[]) obj;
            return fn.apply(args[0], (Object[]) Arrays.copyOfRange(args, 1, args.length));
        };
    }
}

Loading editor...