LeetCode 2650: Design Cancellable Function Solution

Master LeetCode problem 2650 (Design Cancellable Function), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2650. Design Cancellable Function

Hard

Problem Explanation

Explanation

To solve this problem, we need to design a function cancellable that accepts a generator object and returns a cancel function and a promise. The function should handle cancelling the generator by throwing an error back to the generator if cancelled before completion. The generator function may yield promises that need to be resolved or rejected accordingly.

The key steps include:

  1. Execute the generator function, handling promises yielded by the generator.
  2. Implement the cancel functionality by throwing an error "Cancelled" if cancel is called before completion.
  3. Resolve or reject promises based on the generator's behavior.

The time complexity of the solution depends on the number of promises yielded and the cancel time. The space complexity is mainly determined by the number of promises and the size of the generator function.

Solution Code

import java.util.concurrent.*;

class Solution {
    public static Object[] cancellable(Generator generator) {
        CompletableFuture<Object> promise = new CompletableFuture<>();
        Callable<Object> task = () -> {
            try {
                Object result = generator.next(null);
                promise.complete(result);
            } catch (CancellationException e) {
                promise.completeExceptionally(new Exception("Cancelled"));
            } catch (Exception e) {
                promise.completeExceptionally(e);
            }
            return null;
        };
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Object> future = executor.submit(task);
        Runnable cancel = () -> {
            future.cancel(true);
        };
        return new Object[]{cancel, promise};
    }
}

interface Generator {
    Object next(Object value) throws Exception;
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2650 (Design Cancellable Function)?

This page provides optimized solutions for LeetCode problem 2650 (Design Cancellable Function) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2650 (Design Cancellable Function)?

The time complexity for LeetCode 2650 (Design Cancellable Function) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2650 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2650 in Java, C++, or Python.

Back to LeetCode Solutions