Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2776: Convert Callback Based Function to Promise Based Function

In this guide, we solve Leetcode #2776 Convert Callback Based Function to Promise Based Function in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Write a function that accepts another function fn and converts the callback-based function into a promise-based function. The function fn takes a callback as its first argument, along with any additional arguments args passed as separate inputs.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: JavaScript

Intuition

We want to bridge a callback style into an awaitable one.

If we can capture the callback results into a future, we can await it just like a promise.

Approach

Create a wrapper coroutine that constructs a Future, passes a callback into fn, and resolves or rejects the future based on the callback.

Steps:

  • Create a Future.
  • Call fn(callback, *args).
  • Resolve the future on success or set an exception on error.
  • await the future and return its value.

Example

function sum(callback, a, b) { if (a < 0 || b < 0) {   const err = Error('a and b must be positive'); callback(undefined, err);   } else { callback(a + b);   } }

Python Solution

import asyncio def promisify(fn): async def wrapped(*args): loop = asyncio.get_running_loop() future = loop.create_future() def callback(value=None, err=None): if future.done(): return if err is not None: future.set_exception(err) else: future.set_result(value) fn(callback, *args) return await future return wrapped

Complexity

The time complexity is O(1)O(1)O(1) excluding the wrapped function, and the space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy