#2629

Function Composition

Easy
Function CompositionHigher-Order Functions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the same logic as the brute force approach but is more efficient in terms of clarity and execution. We directly create a new function that applies all functions in a single pass without unnecessary complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Define a function that takes an integer 'x'.
  2. 2Step 2: Initialize 'result' with 'x'.
  3. 3Step 3: Loop through the functions in reverse order.
  4. 4Step 4: Update 'result' with the output of each function applied to the current 'result'.
  5. 5Step 5: Return the final 'result'.
solution.py9 lines
1# Full working Python code
2
3def compose(functions):
4    def fn(x):
5        result = x
6        for f in reversed(functions):
7            result = f(result)
8        return result
9    return fn

Complexity note: The time complexity is O(n) because we loop through the functions once. The space complexity is O(1) as we are only using a fixed amount of space for variables.

  • 1Function composition is evaluated from right to left.
  • 2An empty list of functions returns the identity function.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.