Skip to main content
Back to problems
Leetcode
Medium
Functions
Arrays
Recursion
Function Composition

Build a new function by applying a list of functions in sequence to an input value.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Compose Functions

gfg
Problem Statement

Function Composition

You are given an array of functions. Create and return a new function that, when called with one argument, passes that argument through the functions from right to left.

In other words, if the functions are f0,f1,,fn1f_0, f_1, \dots, f_{n-1}, the composed function should behave like:

f0(f1(fn1(x)))f_0(f_1(\dots f_{n-1}(x) \dots ))

If the array of functions is empty, the returned function should behave like the identity function and return its input unchanged.

This problem focuses on understanding function chaining and evaluating a composed pipeline in the correct order.

Input Format

  • An array of functions functions, where each function takes one argument.
  • A single input value x when the returned function is invoked.

Output Format

Return a function that applies the given functions from right to left and produces the final result.

Constraints

  • The number of functions may be zero.
  • Each function is callable with one argument.
  • Preserve the order of composition: the last function in the array runs first.
  • When there are no functions, return the input unchanged.
Examples
Sample cases returned by the problem API.

Example 1

Input

functions = [x => x + 1, x => x * 2, x => x - 3], x = 4

Output

3

Explanation

Apply the functions from right to left: first x - 3 gives 1, then x * 2 gives 2, then x + 1 gives 3.

Example 2

Input

functions = [], x = 10

Output

10

Explanation

With no functions to compose, the returned function acts like the identity function.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.