LeetCode 2715: Timeout Cancellation Solution

Master LeetCode problem 2715 (Timeout Cancellation), a easy 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.

2715. Timeout Cancellation

Easy

Problem Explanation

Explanation

To solve this problem, we need to create a cancellable function that takes the original function fn, its arguments args, and a delay time t. This function should return another function cancelFn that, when invoked, cancels the execution of the original function fn.

We can achieve this by using the setTimeout function to delay the execution of the original function fn by t milliseconds. The cancelFn function can be implemented to clear the timeout, effectively canceling the delayed execution if invoked within the specified time.

Solution Code

import java.util.Timer;
import java.util.TimerTask;

public class TimeoutCancellation {
    public static Runnable cancellable(Runnable fn, long t) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                fn.run();
            }
        }, t);
        
        return timer::cancel;
    }

    public static void main(String[] args) {
        Runnable fn = () -> System.out.println("Delayed function execution");
        long t = 100;
        long cancelTimeMs = 50;
        Runnable cancelFn = cancellable(fn, t);
        new Timer().schedule(new TimerTask() {
            public void run() {
                cancelFn.run();
                System.out.println("Delayed function canceled");
            }
        }, cancelTimeMs);
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2715 (Timeout Cancellation)?

This page provides optimized solutions for LeetCode problem 2715 (Timeout Cancellation) 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 2715 (Timeout Cancellation)?

The time complexity for LeetCode 2715 (Timeout Cancellation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2715 on DevExCode?

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

Back to LeetCode Solutions