#2627

Debounce

Medium
ClosureTimer Management
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 approach uses a single timeout reference to manage the calls efficiently. By leveraging closures, we can ensure that the function is only executed once after the debounce period, regardless of how many times it was called.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to hold the timeout reference.
  2. 2Step 2: When the debounced function is called, clear any existing timeout.
  3. 3Step 3: Set a new timeout to invoke the original function after the specified delay, passing any arguments.
solution.py11 lines
1import threading
2
3def debounce(fn, t):
4    timeout_ref = None
5    def debounced(*args):
6        nonlocal timeout_ref
7        if timeout_ref is not None:
8            timeout_ref.cancel()
9        timeout_ref = threading.Timer(t / 1000, lambda: fn(*args))
10        timeout_ref.start()
11    return debounced

Complexity note: The time complexity is O(n) because we only maintain a single timeout reference, and each function call only requires constant time operations.

  • 1Debouncing is crucial for optimizing performance in event handling.
  • 2Understanding closures and timers is key to implementing debounce effectively.

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