Function Composition - Problem

Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions.

The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))).

The function composition of an empty list of functions is the identity function f(x) = x.

You may assume each function in the array accepts one integer as input and returns one integer as output.

Input & Output

Example 1 — Multiple Functions
$ Input: functions = ["square", "addOne", "double"], x = 4
Output: 34
💡 Note: Composition applies right-to-left: double(addOne(square(4))) = double(addOne(16)) = double(17) = 34
Example 2 — Single Function
$ Input: functions = ["double"], x = 5
Output: 10
💡 Note: Single function: double(5) = 10
Example 3 — Empty Array
$ Input: functions = [], x = 42
Output: 42
💡 Note: Empty function array returns identity function: f(x) = x, so result is 42

Constraints

  • 0 ≤ functions.length ≤ 1000
  • -1000 ≤ x ≤ 1000
  • Each function accepts and returns integers

Visualization

Tap to expand
Function Composition OverviewFunctions Array[f, g, h]Inputx = 4Composition Processh(x) → g(h(x)) → f(g(h(x)))Apply right-to-leftFinal Resultf(g(h(4)))Example: square(4)=16 → addOne(16)=17 → double(17)=34
Understanding the Visualization
1
Input
Array of functions and input value x
2
Compose
Apply functions right-to-left: f(g(h(x)))
3
Output
Return final result of composition
Key Takeaway
🎯 Key Insight: Functions compose right-to-left, creating a pipeline that transforms input through each function in reverse array order
Asked in
Google 25 Microsoft 20
33.2K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen