Partial Function with Placeholders — LeetCode 2797 Python Solution

EasyLeetCode PremiumJavaScript
Problem
#2797
Reading time
3 min

The problem

Given a function fn and an array args, return a function partialFn. Placeholders "_" in the args should be replaced with values from restArgs starting from index 0.

Example

Input
fn = (...args) => args, args = [2,4,6], restArgs = [8,10]
Output
[2,4,6,8,10]
Explanation
const partialFn = partial(fn, args)

Python solution

Python
class Solution:
    def partial(self, fn, args):
        def partial_fn(*restArgs):
            rest_iter = iter(restArgs)
            merged = []
            for a in args:
                if a == "_":
                    try:
                        merged.append(next(rest_iter))
                    except StopIteration:
                        merged.append("_")
                else:
                    merged.append(a)
            merged.extend(list(rest_iter))
            return fn(*merged)

        return partial_fn

Complexity

MeasureComplexity
TimeO(n + m)
SpaceO(n + m) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2797. Partial Function with Placeholders?
LeetCode 2797. Partial Function with Placeholders is rated Easy on LeetCode.
What is the time complexity of LeetCode 2797. Partial Function with Placeholders?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 2797. Partial Function with Placeholders?
The Python solution on this page uses O(n + m) auxiliary space.
What topics does LeetCode 2797. Partial Function with Placeholders cover?
LeetCode 2797. Partial Function with Placeholders is tagged JavaScript on LeetCode.
Is LeetCode 2797. Partial Function with Placeholders a premium problem?
Yes. LeetCode 2797. Partial Function with Placeholders is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview