878590. Function pointer as parameter

Easy

Function Pointer as Parameter

Summary

This problem involves passing a function pointer as a parameter to another function. The key concept is that of function pointers, which are used to point to and invoke other functions. This problem requires understanding how to pass a function as an argument to another function and using it to perform specific operations.

Detailed Explanation

The problem can be thought of as having a function f(x) that takes one argument x. We want to write another function g(f, n) that takes two arguments: the function f and an integer n. The function g should return the value of f(n).

One way to solve this problem is by using a lambda function. A lambda function is a small anonymous function that can take any number of arguments, but can only return one value.

Here's how you can do it:

  1. Write a lambda function f that takes an integer as an argument and returns its square.
  2. Pass this lambda function to the g function along with another integer n.
  3. The g function should call the passed lambda function with the given integer n and return the result.

Here's a step-by-step breakdown of the solution:

  1. Start by defining the f(x) function that takes one argument x and returns its square.
  2. Define the g(f, n) function that takes two arguments: the function f and an integer n.
  3. Inside the g function, call the passed lambda function with the given integer n using the syntax f(n).
  4. Return the result of this operation.

Time complexity for this solution is O(1), as it involves a constant number of operations. Space complexity is also O(1), as it only uses a constant amount of space to store the lambda function and the integer n.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.function.Function;

public class Main {
    public static int g(Function<Integer, Integer> f, int n) {
        return f.apply(n);
    }

    public static void main(String[] args) {
        Function<Integer, Integer> square = x -> x * x;
        System.out.println(g(square, 4)); // prints 16
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.