question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
timeout-cancellation
13/30 days JAVASCRIPT
1330-days-javascript-by-doaaosamak-c7ks
\n# Code\n\n\nvar cancellable = function(fn, args, t) {\n \n var timeout = setTimeout(() =>\n fn(...args)\n , t)\n var cancelFn = () => clearT
DoaaOsamaK
NORMAL
2024-06-20T19:03:02.565095+00:00
2024-06-20T19:03:02.565120+00:00
1,240
false
\n# Code\n```\n\nvar cancellable = function(fn, args, t) {\n \n var timeout = setTimeout(() =>\n fn(...args)\n , t)\n var cancelFn = () => clearTimeout(timeout);\n\n return cancelFn;\n};\n\n```
10
0
['JavaScript']
0
timeout-cancellation
JS - setTimeout / clearTimeout - 2 lines
js-settimeout-cleartimeout-2-lines-by-an-gknc
Intuition\nsetTimeout for fn execution for given time t, return function that executes clearTimeout when called\n\n# Code\n\nconst cancellable = function(fn, ar
Ante_
NORMAL
2023-06-01T19:43:11.519524+00:00
2023-06-01T19:43:11.519549+00:00
1,445
false
# Intuition\nsetTimeout for fn execution for given time t, return function that executes clearTimeout when called\n\n# Code\n```\nconst cancellable = function(fn, args, t) {\n const timeoutHandle = setTimeout(() => fn(...args), t) \n return () => clearTimeout(timeoutHandle)\n};\n```
7
0
['JavaScript']
0
timeout-cancellation
2715. Timeout Cancellation
2715-timeout-cancellation-by-nganthudoan-wiz2
Intuition\nThe code appears to be implementing a cancellable function. The idea is to create a function (cancellable) that takes another function (fn), its argu
nganthudoan2001
NORMAL
2024-01-09T04:40:23.317845+00:00
2024-01-09T04:40:23.317878+00:00
907
false
# Intuition\nThe code appears to be implementing a cancellable function. The idea is to create a function (`cancellable`) that takes another function (`fn`), its arguments (`args`), and a time delay (`t`). This cancellable function returns a new function that, when called, will execute the original function (`fn`) after a specified time delay (`t`). However, the execution can be canceled if another function (returned by `cancellable`) is invoked within a certain time frame.\n\n# Approach\nThe `cancellable` function uses `setTimeout` to delay the execution of the provided function (`fn`). It also returns a cancel function, which clears the timeout, preventing the original function from executing if invoked before the timeout.\n\nIn the provided example:\n- The `fn` function multiplies its argument by 5.\n- The `args` array contains the arguments for `fn`.\n- The time delay is specified by `t`.\n- The `log` function is a helper function that records the time elapsed since the start and the result of calling `fn` with the provided arguments. This information is stored in the `result` array.\n\n# Complexity\n- Time complexity: O(1) for the cancellable function. The time complexity of executing the provided function (`fn`) depends on the function itself.\n- Space complexity: O(1) for the cancellable function. The space complexity of storing results depends on the number of function calls and the data stored in the `result` array.\n\n# Code\n\n\n```javascript\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n let timeoutId;\n\n const cancelFn = () => {\n clearTimeout(timeoutId);\n };\n\n timeoutId = setTimeout(() => {\n const result = fn(...args); \n \n }, t);\n\n return cancelFn;\n};\n\n\n```
4
0
['JavaScript']
0
timeout-cancellation
easy Solution
easy-solution-by-jethwadeven002-1acb
\n# Code\n\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n
jethwadeven002
NORMAL
2024-07-03T07:27:45.853150+00:00
2024-07-03T07:27:45.853177+00:00
899
false
\n# Code\n```\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const t1 = setTimeout(()=>fn(...args), t);\n return () => clearTimeout(t1)\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
3
0
['JavaScript']
0
timeout-cancellation
Beat 95.55% User: Simple Approach
beat-9555-user-simple-approach-by-nishan-1krg
Intuition\nThe cancellable function is designed to create a function that cancels the execution of another function (fn) if it takes longer than a specified tim
nishantpriyadarshi60
NORMAL
2023-10-18T15:48:37.146866+00:00
2023-10-18T15:48:37.146974+00:00
703
false
# Intuition\nThe cancellable function is designed to create a function that cancels the execution of another function (fn) if it takes longer than a specified time (t). It uses a timer to achieve this. If the timer expires before fn completes, it will prevent the function from executing.\n\n# Approach\n1. The cancellable function takes three parameters:\n\nfn: The function to be executed.\nargs: An array of arguments to pass to the function fn.\nt: The time limit in milliseconds. If fn doesn\'t complete within this time, it will be canceled.\nInside the cancellable function:\n\n2. It sets up a timer using setTimeout that will execute fn(...args) after a delay of t milliseconds.\nIt returns a function that can be used to cancel the timer.\n3. The returned cancel function, when called, uses clearTimeout to cancel the execution of fn if it hasn\'t already started.\n\n# Complexity\n- Time complexity:\no(1)\n\n- Space complexity:\no(1)\n\n# Code\n```\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timeOut = setTimeout(() => {\n fn(...args)\n },t)\n return function(){\n clearTimeout(timeOut)\n }\n};\n\n/**\n * const result = []\n *\n * const fn = (x) => x * 5\n * const args = [2], t = 20, cancelT = 50\n *\n * const start = performance.now() \n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)})\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelT)\n * \n * setTimeout(() => {\n * cancel()\n * }, cancelT)\n *\n * setTimeout(() => {\n * console.log(result) // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n\n\n```
3
0
['JavaScript']
0
timeout-cancellation
Simple solution with walk through 🤝👍
simple-solution-with-walk-through-by-sus-okxk
Approach\n Describe your approach to solving the problem. \n1. The cancellable function takes three parameters: fn, args, and t.\n\n2. fn is the function to be
sushmitha1227
NORMAL
2023-06-15T02:16:50.373310+00:00
2023-06-15T02:16:50.373336+00:00
500
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The cancellable function takes three parameters: `fn`, `args`, and `t`.\n\n2. `fn` is the function to be executed after a delay.\n`args` is an array of arguments to be passed to the function `fn`.\n`t` is the delay in milliseconds.\nInside the `cancellable` function, a variable `cancel` is initialized to false. This variable will be used to determine if the execution of the delayed function should be canceled.\n\n3. The `setTimeout` function is called with an arrow function as the callback. This arrow function checks the value of `cancel` and executes the function fn with the provided arguments `...args` only if `cancel` is false. The timeout value is set to `t` milliseconds.\n\n4. The `setTimeout` function schedules the execution of the arrow function after the specified delay.\n\n5. Finally, the `cancellable` function returns another function. This returned function is used to cancel the execution of the delayed function.\n When the returned function is invoked, it sets `cancel` to true, effectively canceling the execution of `fn` if it hasn\'t occurred yet.\n\n# Complexity\n- Time complexity:\nO(max(t,cancelT))\n\n# Code\n```\nvar cancellable = function(fn, args, t) {\n let cancel = false;\n setTimeout(() =>!cancel && fn(...args),t)\n return () => cancel = true\n};\n```
3
0
['JavaScript']
0
timeout-cancellation
Easy Solution✔ || JavaScript 🎁🎁
easy-solution-javascript-by-deleted_user-ktcl
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
deleted_user
NORMAL
2023-06-02T00:39:30.768796+00:00
2023-06-02T00:39:30.768839+00:00
2,235
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n let timeoutId;\n\n const cancelFn = () => clearTimeout(timeoutId);\n\n timeoutId = setTimeout(() => fn(...args), t);\n\n return cancelFn; \n};\n\n/**\n * const result = []\n *\n * const fn = (x) => x * 5\n * const args = [2], t = 20, cancelT = 50\n *\n * const log = (...argsArr) => {\n * result.push(fn(...argsArr))\n * }\n * \n * const cancel = cancellable(fn, args, t);\n * \n * setTimeout(() => {\n * cancel()\n * console.log(result) // [{"time":20,"returned":10}]\n * }, cancelT)\n */\n```
3
0
['JavaScript']
1
timeout-cancellation
Simple explanation
simple-explanation-by-mahima5687-a7f0
What is asked in question?The problem is asking you to create a function cancellable that takes three arguments:1. fn: A function that you want to execute after
mahima5687
NORMAL
2025-03-03T09:49:36.238927+00:00
2025-03-03T09:49:36.238927+00:00
266
false
# What is asked in question? --- The problem is asking you to create a function `cancellable` that takes three arguments: **1. `fn:`** A function that you want to execute after a delay. **2. `args:`** An array of arguments that you want to pass to the function `fn`. **3. `t:`** A delay time in milliseconds after which the function `fn` should be executed. The `cancellable` function should return another function `cancelFn` that, when called, will cancel the execution of `fn` if it hasn't already been executed. Additionally, there is a `cancelTimeMs` delay that determines when the `cancelFn` function will be invoked. If `cancelFn` is invoked before the delay `t` has passed, the execution of `fn` should be canceled. If `cancelFn` is not invoked within the delay `t`, then `fn` should be executed with the provided `args`. --- # Example Breakdown --- **Example 1:** - `fn = (x) => x * 5` - `args = [2]` - `t = 20` (milliseconds) - `cancelTimeMs = 50` (milliseconds) In this case: - The function `fn` is scheduled to execute after 20ms. - The `cancelFn` is scheduled to be called after 50ms. - Since 50ms is after 20ms, `fn` will execute at 20ms, and the cancellation will have no effect. **`Output: [{"time": 20, "returned": 10}]`** --- **Example 2:** - `fn = (x) => x**2` - `args = [2]` - `t = 100` (milliseconds) - `cancelTimeMs = 50` (milliseconds) In this case: - The function `fn` is scheduled to execute after 100ms. - The `cancelFn` is scheduled to be called after 50ms. - Since 50ms is before 100ms, `cancelFn` will be called first, canceling the execution of `fn`. **`Output: []`** --- # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { // Schedule the function fn to be executed after t milliseconds const timeoutId = setTimeout(() => { fn(...args); }, t); // Define the cancelFn function const cancelFn = () => { clearTimeout(timeoutId); // Cancel the execution of fn }; // Return the cancelFn function return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ``` --- # Explanation of the Code --- **1. Scheduling `fn` Execution:** - We use `setTimeout` to schedule the execution of `fn` after `t` milliseconds. The `setTimeout` function returns a `timeoutId` that we can use to cancel the timeout if needed. **2. Defining `cancelFn`:** - The `cancelFn` function uses `clearTimeout(timeoutId)` to cancel the scheduled execution of `fn`. If `cancelFn` is called before `fn` is executed, `fn` will not run. **3. Returning cancelFn:** - The `cancellable` function returns `cancelFn`, which can be called later to cancel the execution of `fn`. **4. Example Usage:** - In the example, `cancelFn` is scheduled to be called after `cancelTimeMs` (50ms). Depending on the value of `t` and `cancelTimeMs`, `fn` will either execute or be canceled. This implementation ensures that the function `fn` is only executed if it is not canceled within the specified delay `t`. --- ![upvote.jpg](https://assets.leetcode.com/users/images/aff3220e-a219-4787-ac48-d4d9abdee1c6_1740995340.1806433.jpeg)
2
0
['JavaScript']
1
timeout-cancellation
2715. Timeout Cancellation solution 🚀
2715-timeout-cancellation-solution-by-it-pmj2
IntuitionThe problem involves executing a function fn after a specified delay t, with the option to cancel the execution before the delay ends. This requires a
its_me_1
NORMAL
2025-01-04T10:12:05.666991+00:00
2025-01-04T10:12:05.666991+00:00
162
false
# Intuition The problem involves executing a function fn after a specified delay t, with the option to cancel the execution before the delay ends. This requires a mechanism to schedule and potentially cancel the execution, which can be efficiently handled using JavaScript's setTimeout and clearTimeout functions. By storing the timer ID returned by setTimeout, we can later cancel the scheduled execution if needed. # Approach 1 - Use setTimeout to schedule the execution of fn with the provided arguments args after t milliseconds. 2 - Store the timer ID returned by setTimeout. 3 - Define a cancelFn function that uses clearTimeout with the stored timer ID to cancel the execution. 4 - Return the cancelFn from the cancellable function, allowing the caller to cancel the scheduled execution if needed. # Complexity - Time complexity: Both setting up a timeout with setTimeout and canceling it with clearTimeout are constant-time operations. - Space complexity: The space usage is constant as it involves storing only the timer ID and the minimal state required for function execution. ![upvote pls.png](https://assets.leetcode.com/users/images/d2d25737-0486-4221-807f-608467c6de0c_1735985509.4099817.png) # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timerId = setTimeout(() => { fn(...args); }, t); return function cancelFn() { clearTimeout(timerId); }; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
2
0
['JavaScript']
0
timeout-cancellation
Cancellable Function Solution with Full Testing Breakdown
cancellable-function-solution-with-full-oyky5
Intuition\nWe need to delay the execution of a function named fn which will be passed as an argument to our cancallable() function. The trick is we need to canc
noxtrah
NORMAL
2024-09-07T14:53:52.965917+00:00
2024-09-07T14:53:52.965935+00:00
25
false
# Intuition\nWe need to delay the execution of a function named `fn` which will be passed as an argument to our `cancallable()` function. The trick is we need to cancel the execution of `fn()` if the cancel function `cancelFn` is invoked before `fn()` is executed.\n\n# Approach\nIn order to solve this problem, we need to:\n\n1. Call `setTimeout()` function to delay the execution of `fn` by `t` amount of time. But calling this function is not enough alone, we also store the timeout ID which will be returned from `setTimeout()`. We need this `timeoutID` because in the next step we are going to use it in another function.\n\n2. Now define a new function named `cancelFn` as inner function. This function doesn\'t return any value, but it will execute `clearTimeout()` function when it\'s called. In other words, our outer function `cancellable` will return `cancelFn`, but our inner function `cancelFn` won\'t return anything. It will just call `clearTimeout()`.The javaScript function `clearTimeout()` simply takes a parameter as timeoutID, because it should know which timeout it going to clear. That is why we stored `timeoutID` of `setTimeout()` in step 1.\n\n3. Last step is returning `cancelFn`. That\'s it.\n\n# Description\n```\nconst start = performance.now();\n```\n\n`performance.now()` captures current time. This is going to used to measure the execution time.\n\n```\nconst log = (...argsArr) => {\n const diff = Math.floor(performance.now() - start);\n result.push({"time": diff, "returned": fn(...argsArr)});\n}\n```\n\nHere `diff` will be the time difference between the start time of code and call time of `log(...argsArr)` function. Then it pushed the variable `diff` and the result of function which is `fn(...argsArr)` to the array named `result`. Later this `log(...argsArr)` function will be passed to the `cancellable()` function as an argument.\n\n```\nconst cancel = cancellable(log, args, t);\n```\n\nThe return value of `cancellable()` which is `cancelFn()` is assigned to the `cancel`. `log`,`args`, and `t` are passed as argument to the `cancellable(log, args, t)`.\nIf you wonder why it has passed `log()` instead of `fn()` to the `cancellable()`, the first parameter of `cancellable()` was `fn` by default not `log`, then the answer is: `fn()` function is already called and pushed to the `result` array inside `log()` function. Moreover the `log()` function consist of time `diff` which is going to used in testing the code by checking the time. So instead of passing the time `diff` and the `fn()` function iteself, they merged these two inside of one function named `log()`.\n\n```\nconst maxT = Math.max(t, cancelTimeMs);\n```\n\n`Math.max()` decides which of it\'s arguments is bigger. It assigns bigger integer to the `maxT`. This variable will be used to log the result after execution/cancellation of `fn()`.\n\n```\nsetTimeout(cancel, cancelTimeMs);\n```\n\nThis line schedules the execution of `cancel()`, which is `cancelFn`, to occur after `cancelTimeMs` milliseconds.\nSo if the argument `fn()` in `cancellable()` doesn\'t execute before `cancelTimeMs`, the Schedule will be cancelled.\nIn other words, if we want to execute `fn()`, then `t` must be lower or equal to the `cancelTimeMs`. \n\n```\n setTimeout(() => {\n console.log(result);\n }, maxT + 15)\n```\n\nThis part just prints the result to the console after `maxT` + 15 miliseconds. Since we want to test it, we should see the output in the console. Thus result should be executed after `t` or `cancelTimeMs` whichever is higher. + 15 is just a small additional delay to ensure that the previous `setTimeout()` have completed before the result is logged.\n\n\n# Complexity\n- Time complexity:\nSince `setTimeout()` and `clearTimeout()` functions ocur in constant time regardless of the input size, the time complexity will be: \n\n $$O(1)$$\n\n\n- Space complexity:\nIn this solution we only stored one variable(`timeoutID`),and a function reference(`cancelFn()`). Thus the space complexity will be: \n\n $$O(1)$$\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n let timeoutId;\n\n const cancelFn = () => {\n clearTimeout(timeoutId);\n };\n\n timeoutId = setTimeout(() => {\n fn(...args);\n }, t);\n\n return cancelFn;\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
2
0
['JavaScript']
0
timeout-cancellation
Easy JS Solution | No Explanation Required | Clean Code
easy-js-solution-no-explanation-required-suf0
\n# Code\n\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n
shubhaamtiwary_01
NORMAL
2023-09-10T13:27:03.373806+00:00
2023-09-10T13:27:03.373840+00:00
368
false
\n# Code\n```\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timeout = setTimeout(()=>{\n fn(...args);\n },t)\n return cancel=()=>{\n clearTimeout(timeout);\n }\n};\n\n/**\n * const result = []\n *\n * const fn = (x) => x * 5\n * const args = [2], t = 20, cancelT = 50\n *\n * const start = performance.now() \n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)})\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelT)\n * \n * setTimeout(() => {\n * cancel()\n * }, cancelT)\n *\n * setTimeout(() => {\n * console.log(result) // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
2
0
['JavaScript']
0
timeout-cancellation
Easy approach towards problem
easy-approach-towards-problem-by-rahul_b-ae8b
Intuition\n Describe your first thoughts on how to solve this problem. \nThis requires clearTimeout funtion which cancels a timeout previously established by ca
rahul_batra
NORMAL
2023-08-29T04:34:25.664620+00:00
2023-08-29T04:34:25.664645+00:00
210
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis requires clearTimeout funtion which cancels a timeout previously established by calling setTimeout().\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst to make a timer for function execution for time t and cancelFn function for cancelling that timeout event. \nconst cancel = cancellable(log, args, t);\nand cancel would get cancelfn function returned from cancellable. \n \n setTimeout(() => { cancel()\n }, cancelT)\n\n\n\n\n# Code\n```\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\n\nvar cancellable = function(fn, args, t) {\n const timer = setTimeout(()=> {\n fn(...args);\n }, t);\n\n const cancelFn = function(){\n clearTimeout(timer);\n }\n return cancelFn;\n};\n\n\n/**\n * const result = []\n *\n * const fn = (x) => x * 5\n * const args = [2], t = 20, cancelT = 50\n *\n * const start = performance.now() \n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr))\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelT)\n * \n * setTimeout(() => {\n * cancel()\n * }, cancelT)\n *\n * setTimeout(() => {\n * console.log(result) // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
2
0
['JavaScript']
0
timeout-cancellation
🌱 Simple Solution | 2 liner 🚀
simple-solution-2-liner-by-subroto823-0c54
\n\n# Code\n\nvar cancellable = function(fn, args, t) {\n let timeoutId = setTimeout(() => fn(...args), t);\n return () => clearTimeout(timeoutId);\n};\n\
subroto823
NORMAL
2023-08-14T06:32:55.669747+00:00
2023-08-27T21:31:31.086331+00:00
216
false
\n\n# Code\n```\nvar cancellable = function(fn, args, t) {\n let timeoutId = setTimeout(() => fn(...args), t);\n return () => clearTimeout(timeoutId);\n};\n\n```
2
0
['JavaScript']
0
timeout-cancellation
Simple JS Solution
simple-js-solution-by-gokulram2221-wrm3
Code
gokulram2221
NORMAL
2025-04-12T09:38:24.513337+00:00
2025-04-12T09:38:24.513337+00:00
1
false
# Code ```javascript [] const cancellable = (fn, args, t) => { const timer = setTimeout(() => fn(...args), t); return () => clearTimeout(timer); }; ```
1
0
['JavaScript']
0
timeout-cancellation
JavaScript
javascript-by-adchoudhary-c2ly
Code
adchoudhary
NORMAL
2025-03-01T09:46:48.607443+00:00
2025-03-01T09:46:48.607443+00:00
94
false
# Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timeoutId = setTimeout(function() { fn.apply(null, args); }, t); const cancelFn = function() { clearTimeout(timeoutId); }; return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
1
0
['JavaScript']
0
timeout-cancellation
easy js solution to understand
easy-js-solution-to-understand-by-pratik-bzdl
IntuitionApproachComplexity Time complexity: Space complexity: Code
pratik5722
NORMAL
2025-02-25T09:19:54.075433+00:00
2025-02-25T09:19:54.075433+00:00
119
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { function cancelFn () { clearTimeout(timer); }; const timer = setTimeout(() => { fn(...args) }, t); return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
1
0
['JavaScript']
0
timeout-cancellation
👉🏻BEAT 76.41% || EASY TO UNDERSTAND SOLUTION || JS
beat-7641-easy-to-understand-solution-js-txi0
IntuitionApproachComplexity Time complexity: Space complexity: Code
Siddarth9911
NORMAL
2025-01-25T15:59:27.685666+00:00
2025-01-25T15:59:27.685666+00:00
208
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] var cancellable = function(fn, args, t) { const timeoutId = setTimeout(() => {fn(...args);}, t); return function() {clearTimeout(timeoutId);}; }; ```
1
0
['JavaScript']
0
timeout-cancellation
Timeout in JavaScript and TypeScript
timeout-in-javascript-and-typescript-by-qrtkc
Complexity Time complexity: O(1) Space complexity: O(1) Code
x2e22PPnh5
NORMAL
2025-01-25T06:48:00.684944+00:00
2025-01-25T09:51:29.710429+00:00
193
false
# Complexity - Time complexity: O(1) - Space complexity: O(1) # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timeoutID = setTimeout(() => { fn.apply(null, args); }, t); const cancelFn = () => clearTimeout(timeoutID); return cancelFn; }; ``` ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (...args: JSONValue[]) => void function cancellable(fn: Fn, args: JSONValue[], t: number): Function { const timeoutID: ReturnType<typeof setTimeout> = setTimeout(() => { fn.apply(null, args); }, t); const cancelFn: Function = () => clearTimeout(timeoutID); return cancelFn; }; ```
1
0
['TypeScript', 'JavaScript']
0
timeout-cancellation
Easy Solution with O(1) Complexity
easy-solution-with-o1-complexity-by-prat-9cwa
ExplanationUnderstand Requirements:A function cancellable takes three parameters: fn: A function to be executed after the delay. args: An array of arguments to
pratyushpanda91
NORMAL
2025-01-14T15:33:53.199562+00:00
2025-01-14T15:33:53.199562+00:00
214
false
# Explanation ### Understand Requirements: A function cancellable takes three parameters: fn: A function to be executed after the delay. args: An array of arguments to be passed to fn when it is executed. t: Delay time in milliseconds before fn is executed. ### The cancellable function should return a cancelFn: If cancelFn is called before the t delay expires, the execution of fn is cancelled. If cancelFn is not called, fn executes after the delay with args passed to it. ### Key JavaScript Concepts: setTimeout: Schedule the execution of fn after t milliseconds. clearTimeout: Cancel the timeout if cancelFn is invoked before the timeout expires. Tracking Time: Use Date.now() or other methods to log when the execution or cancellation happens. ### Steps: Use setTimeout to schedule the execution of fn. Store the timeoutId returned by setTimeout. Define and return the cancelFn that calls clearTimeout with the stored timeoutId. ### Implementation: Wrap the logic in a function cancellable that adheres to the problem's requirements. Ensure cancelFn cancels the fn execution cleanly and efficiently. ### Edge Cases: Cancellation happens exactly at the timeout (t ms). The fn execution is delayed but not cancelled. ## Complexity Analysis ### Time Complexity: setTimeout and clearTimeout are O(1), as scheduling and cancelling timeouts have constant complexity. Overall: O(1). ### Space Complexity: Storage for timeoutId and minimal memory for scheduling the timeout. Overall: O(1). # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ function cancellable(fn, args, t) { let timeoutId; // Schedule the execution of fn after t milliseconds timeoutId = setTimeout(() => { fn(...args); }, t); // Return the cancel function return () => { clearTimeout(timeoutId); // Cancels the scheduled execution }; } /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
1
0
['JavaScript']
0
timeout-cancellation
Easy Solution using setTimeout() and clearTimeout()
easy-solution-using-settimeout-and-clear-v2ux
Intuition\nWe can schedule the function excution using setTimeout function and cancel it using clearTimeout function.\n\n# Approach\nWe pass the given function
xebec19
NORMAL
2024-11-22T05:51:19.694899+00:00
2024-11-22T05:51:19.694938+00:00
104
false
# Intuition\nWe can schedule the function excution using setTimeout function and cancel it using clearTimeout function.\n\n# Approach\nWe pass the given function and arguments to setTimeout to schedule its execution after given time. Then we would return a function which simply clear that schedule, hence cancelling the execution.\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timeoutID = setTimeout(() => fn.apply(this,args),t);\n\n return () => {\n clearTimeout(timeoutID);\n }\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
1
0
['JavaScript']
0
timeout-cancellation
Easy solution ✅
easy-solution-by-apophis29-3ziv
\nTime Complexity:O(1)\nSpace Complexity:O(1)\n\n\n```\n/*\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n /\nva
Apophis29
NORMAL
2024-02-09T17:27:22.115483+00:00
2024-02-09T17:27:22.115515+00:00
408
false
\nTime Complexity:O(1)\nSpace Complexity:O(1)\n\n\n```\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timeoutId = setTimeout(function() {\n fn.apply(null, args);\n }, t);\n\n const cancelFn = function() {\n clearTimeout(timeoutId);\n };\n\n return cancelFn;\n};\n\n````\nThankyou:).
1
0
[]
1
timeout-cancellation
ClearTimeout Solution (with step by step explanation)
cleartimeout-solution-with-step-by-step-awtov
Intuition\nwe will use clearTimeout to clear timeout\n# Approach\nwe declare timerId that will hold id of setTimeout call, and then we return function in which
alekseyvy
NORMAL
2023-11-05T22:28:12.850896+00:00
2023-11-05T22:28:12.850912+00:00
530
false
# Intuition\nwe will use clearTimeout to clear timeout\n# Approach\nwe declare timerId that will hold id of setTimeout call, and then we return function in which we call clearTimeout with timerId\n# Complexity\n- Time complexity:\nO(1)\n- Space complexity:\nO(1)\n# Code\n```\ntype JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };\ntype Fn = (...args: JSONValue[]) => void\n\nfunction cancellable(fn: Fn, args: JSONValue[], t: number): Function {\n // declare timerId and call setTimeout\n const timerId = setTimeout(() => {\n fn(...args)\n }, t)\n // return function:\n\treturn () => {\n // call clearTimeout with timerId\n clearTimeout(timerId);\n }\n};\n\n/**\n * const result = []\n *\n * const fn = (x) => x * 5\n * const args = [2], t = 20, cancelT = 50\n *\n * const start = performance.now() \n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)})\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelT)\n * \n * setTimeout(() => {\n * cancel()\n * }, cancelT)\n *\n * setTimeout(() => {\n * console.log(result) // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
1
0
['TypeScript']
1
timeout-cancellation
✅Clear & Easy solution || 90% efficient🔥
clear-easy-solution-90-efficient-by-maya-49tf
Approach\nseTimeout() : The setTimeout() method sets a timer which executes a function or specified piece of code once after timer expires.\nThe function is Onl
mayankpandey3
NORMAL
2023-10-02T14:29:09.239098+00:00
2023-10-02T14:29:09.239115+00:00
117
false
# Approach\n***seTimeout()*** : The setTimeout() method sets a timer which executes a function or specified piece of code once after timer expires.\n**The function is Only executed ONCE**\n\n***clearTimeout()*** : The clearTimeout() method cancels a timeout previously established by *setTimeout()*\n\n# Code\n```\nvar cancellable = function(fn, args, t) {\n var timeout = setTimeout(()=> fn(...args), t);\n return cancelFn = ()=>clearTimeout(timeout);\n};\n```
1
0
['JavaScript']
1
timeout-cancellation
<JavaScript>
javascript-by-preeom-ciu3
Code\n\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n con
PreeOm
NORMAL
2023-08-13T06:08:16.517018+00:00
2023-08-13T06:08:16.517037+00:00
1,194
false
# Code\n```\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timeoutId = setTimeout(function() {\n fn.apply(null, args);\n }, t);\n\n const cancelFn = function() {\n clearTimeout(timeoutId);\n };\n\n return cancelFn;\n};\n\n/**\n * const result = []\n *\n * const fn = (x) => x * 5\n * const args = [2], t = 20, cancelT = 50\n *\n * const start = performance.now() \n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr))\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelT)\n * \n * setTimeout(() => {\n * cancel()\n * }, cancelT)\n *\n * setTimeout(() => {\n * console.log(result) // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
1
0
['JavaScript']
0
timeout-cancellation
TS : Very simple approach | setTimeout, clearTimeout
ts-very-simple-approach-settimeout-clear-g8bw
Code\n```\nfunction cancellable(fn: Function, args: any[], t: number): Function {\n const timeoutId = setTimeout(()=>{\n fn(...args)\n },t);\n\n
Jitendra-kaswa
NORMAL
2023-07-13T05:55:35.995712+00:00
2023-07-13T05:55:35.995732+00:00
60
false
# Code\n```\nfunction cancellable(fn: Function, args: any[], t: number): Function {\n const timeoutId = setTimeout(()=>{\n fn(...args)\n },t);\n\n const cancelFn:Function = ()=>{\n clearTimeout(timeoutId);\n }\n return cancelFn;\n};\n
1
0
['TypeScript']
0
timeout-cancellation
TS : Very simple approach | setTimeout, clearTimeout
ts-very-simple-approach-settimeout-clear-a9kp
Code\n```\nfunction cancellable(fn: Function, args: any[], t: number): Function {\n const timeoutId = setTimeout(()=>{\n fn(...args)\n },t);\n\n
Jitendra-kaswa
NORMAL
2023-07-13T05:55:34.405020+00:00
2023-07-13T05:55:34.405064+00:00
22
false
# Code\n```\nfunction cancellable(fn: Function, args: any[], t: number): Function {\n const timeoutId = setTimeout(()=>{\n fn(...args)\n },t);\n\n const cancelFn:Function = ()=>{\n clearTimeout(timeoutId);\n }\n return cancelFn;\n};\n
1
0
['TypeScript']
0
timeout-cancellation
[JS] easy use of setTimeout & clearTimeout
js-easy-use-of-settimeout-cleartimeout-b-13kx
javascript\nvar cancellable = function(fn, args, t) { \n let timerId = setTimeout(fn, t, ...args);\n let cancelFn = () => clearTimeout(timerId);\n\n
pbelskiy
NORMAL
2023-06-24T13:31:39.047446+00:00
2023-06-24T13:31:39.047479+00:00
445
false
```javascript\nvar cancellable = function(fn, args, t) { \n let timerId = setTimeout(fn, t, ...args);\n let cancelFn = () => clearTimeout(timerId);\n\n return cancelFn;\n};\n```
1
0
[]
1
timeout-cancellation
1-liner
1-liner-by-0x81-12ky
js\nconst cancellable =\n (f, a, t, c = setTimeout(f, t, ...a)) => () => clearTimeout(c)\n
0x81
NORMAL
2023-06-01T22:05:24.893714+00:00
2023-06-01T22:43:43.856390+00:00
112
false
```js\nconst cancellable =\n (f, a, t, c = setTimeout(f, t, ...a)) => () => clearTimeout(c)\n```
1
0
['JavaScript']
0
timeout-cancellation
solution
solution-by-nealeshka-teto
IntuitionApproachComplexity Time complexity: Space complexity: Code
NeAleshka
NORMAL
2025-04-12T00:16:29.894127+00:00
2025-04-12T00:16:29.894127+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timeoutId = setTimeout(() => { fn(...args); }, t); const cancelFn = () => { clearTimeout(timeoutId); }; return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
1 liner code with comments
1-liner-code-with-comments-by-hawk2a-6zyr
CodeWith comments
hawk2a
NORMAL
2025-04-06T23:51:11.978245+00:00
2025-04-06T23:51:11.978245+00:00
3
false
# Code ```javascript [] const cancellable = (fn, args, t) => { const timeoutId = setTimeout(() => fn(...args), t); return () => clearTimeout(timeoutId); }; ``` # With comments ``` const cancellable = (fn, args, t) => { // 1. `setTimeout()` is used to delay the execution of `fn` (the function) with provided `args` (the arguments). // The function `fn` will be called after `t` milliseconds (the delay time). const timeoutId = setTimeout(() => fn(...args), t); // 2. The `return` statement gives back a function (the cancel function). // This cancel function can be called later to clear the timeout before the function `fn` is executed. return () => clearTimeout(timeoutId); }; ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-naeem_abd-i0ay
ExplanationUnderstand Requirements:A function cancellable takes three parameters: fn: A function to be executed after the delay. args: An array of arguments to
Naeem_ABD
NORMAL
2025-04-02T09:05:16.024909+00:00
2025-04-02T09:05:16.024909+00:00
6
false
# Explanation # Understand Requirements: A function cancellable takes three parameters: fn: A function to be executed after the delay. args: An array of arguments to be passed to fn when it is executed. t: Delay time in milliseconds before fn is executed. The cancellable function should return a cancelFn: If cancelFn is called before the t delay expires, the execution of fn is cancelled. If cancelFn is not called, fn executes after the delay with args passed to it. # Key JavaScript Concepts: setTimeout: Schedule the execution of fn after t milliseconds. clearTimeout: Cancel the timeout if cancelFn is invoked before the timeout expires. Tracking Time: Use Date.now() or other methods to log when the execution or cancellation happens. # Steps: Use setTimeout to schedule the execution of fn. Store the timeoutId returned by setTimeout. Define and return the cancelFn that calls clearTimeout with the stored timeoutId. # Implementation: Wrap the logic in a function cancellable that adheres to the problem's requirements. Ensure cancelFn cancels the fn execution cleanly and efficiently. # Edge Cases: Cancellation happens exactly at the timeout (t ms). The fn execution is delayed but not cancelled. # Complexity Analysis # Time Complexity: setTimeout and clearTimeout are O(1), as scheduling and cancelling timeouts have constant complexity. Overall: O(1). # Space Complexity: Storage for timeoutId and minimal memory for scheduling the timeout. Overall: O(1). # Code ```javascript [] function cancellable(fn, args, t) { let timeoutId; // Schedule the execution of fn after t milliseconds timeoutId = setTimeout(() => { fn(...args); }, t); // Return the cancel function return () => { clearTimeout(timeoutId); // Cancels the scheduled execution }; } ```
0
0
['JavaScript']
0
timeout-cancellation
2715. Timeout Cancellation
2715-timeout-cancellation-by-4php4dnz3e-v81w
IntuitionThe goal is to execute a function fn with the given arguments args after a delay of t milliseconds. However, we also need a way to cancel the execution
4pHP4dNZ3e
NORMAL
2025-03-31T08:06:53.415817+00:00
2025-03-31T08:06:53.415817+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The goal is to execute a function `fn` with the given arguments `args` after a delay of `t` milliseconds. However, we also need a way to cancel the execution if needed before `t` milliseconds elapse. - We can schedule the execution using `setTimeout()`. - To allow cancellation, we store the timeout ID and use `clearTimeout()` to stop execution if the cancel function is called before the timeout completes. # Approach <!-- Describe your approach to solving the problem. --> 1. **Define the cancellable function** - It takes `fn`, `args`, and `t` as input. - `setTimeout()` is used to delay the function execution. 2. **Schedule function execution** - Call `fn(...args)` inside a `setTimeout()` after `t` milliseconds. - Store the timeout ID in a variable (`timer`). 3. **Provide a cancellation mechanism** - Define a `cancel` function that calls `clearTimeout(timer)`. - Return `cancel` so it can be used later to prevent execution. 4. **Example Flow** - The function is scheduled to execute after `t` milliseconds. - If `cancel()` is called before `t`, execution is prevented. - Otherwise, `fn(...args)` executes normally. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - **Best Case (Cancellation Before Execution)** - `setTimeout()` → `O(1)` - `clearTimeout()` → `O(1)` - **Total: O(1)** - **Worst Case (Execution Happens)** - `setTimeout()` → `O(1)` - `fn(...args)` executes in its own complexity (assume `O(1)`). - **Total: O(1)** Thus, the overall **time complexity is O(1)**. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> - We store only one variable (`timer`) → **O(1)**. - The function does not use additional space. - `setTimeout()` holds a function reference in memory, but this is a constant overhead. # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { // return function () const cancel = () => { clearTimeout(timer); } const timer = setTimeout(() => { fn(...args); }, t); return cancel; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
2715.Leetcode- Timeout Cancellation Solution
2715leetcode-timeout-cancellation-soluti-2vb8
IntuitionThis problem is about asynchronous execution control, specifically handling timeouts and cancellations. In JavaScript, we use setTimeout to schedule fu
runl4AVDwJ
NORMAL
2025-03-28T13:29:58.724301+00:00
2025-03-28T13:29:58.724301+00:00
3
false
# **Intuition** This problem is about **asynchronous execution control**, specifically handling **timeouts and cancellations**. In JavaScript, we use `setTimeout` to schedule function execution, but we also need a way to **cancel** it before execution if required. By returning a **cancellation function**, we allow users to clear the timeout before it executes. This is useful in scenarios like: ✅ **Debouncing input fields** ✅ **Cancelling API calls** ✅ **Optimizing event listeners** --- # **Understanding `setTimeout` & Cancellation** ✅ **What is `setTimeout`?** `setTimeout` is a built-in JavaScript function used to delay function execution for a specified time (in milliseconds). ✅ **How to Cancel a Timeout?** We use `clearTimeout(timeoutID)`, where `timeoutID` is the value returned by `setTimeout`. This prevents the function from running if the timeout is cleared before execution. --- # **Approach** I explored **two different approaches** to solve this problem: --- # 🔹 **Approach 1: Using `setTimeout` with Explicit Clear** ```js var cancellable = function(fn, args, t) { let timer = setTimeout(() => { fn(...args); }, t); return () => { clearTimeout(timer); }; }; ``` 📌 **Explanation:** - `setTimeout` schedules function execution after `t` milliseconds. - The returned function (`cancellable`) stores the timeout reference. - If the user calls this function, `clearTimeout(timer)` cancels execution. ✅ **Pros:** - Simple and easy to understand. - Works well for basic timeout cancellations. --- # 🔹 **Approach 2: Passing Arguments Directly to `setTimeout`** ```js var cancellable = function(fn, args, t) { let timer = setTimeout(fn, t, ...args); return () => clearTimeout(timer); }; ``` 📌 **Key Differences:** - Instead of using an arrow function inside `setTimeout`, we pass `fn` directly with arguments. - Reduces function wrapping overhead, making it slightly more efficient. ✅ **Pros:** - More concise than Approach 1. - Uses **native `setTimeout` argument passing**, which improves readability. --- # **Complexity Analysis** - **Time Complexity:** - $$O(1)$$ – `setTimeout` and `clearTimeout` are constant-time operations. - **Space Complexity:** - $$O(1)$$ – We store only a single timeout reference. --- # **Code Implementation** ```js /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timer = setTimeout(fn, t, ...args); return () => clearTimeout(timer); }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15); */ ``` --- # **Important Topics to Learn 📚** - **JavaScript Timers (`setTimeout`, `clearTimeout`)**: Controlling function execution timing. - **Asynchronous Execution**: Handling delayed execution in JavaScript. - **Function Closures**: Returning functions with access to outer variables. - **Higher-Order Functions**: Functions that return other functions (like our cancellable function). --- # 🚀 **Support & Feedback** ✅ If you found this helpful, **please upvote & comment** on my solution! 💬 Let’s discuss alternative solutions & improvements! 🚀
0
0
['JavaScript']
0
timeout-cancellation
2715.Leetcode- Timeout Cancellation Solution
2715leetcode-timeout-cancellation-soluti-jhx3
IntuitionThis problem is about asynchronous execution control, specifically handling timeouts and cancellations. In JavaScript, we use setTimeout to schedule fu
runl4AVDwJ
NORMAL
2025-03-28T13:29:56.339463+00:00
2025-03-28T13:29:56.339463+00:00
1
false
# **Intuition** This problem is about **asynchronous execution control**, specifically handling **timeouts and cancellations**. In JavaScript, we use `setTimeout` to schedule function execution, but we also need a way to **cancel** it before execution if required. By returning a **cancellation function**, we allow users to clear the timeout before it executes. This is useful in scenarios like: ✅ **Debouncing input fields** ✅ **Cancelling API calls** ✅ **Optimizing event listeners** --- # **Understanding `setTimeout` & Cancellation** ✅ **What is `setTimeout`?** `setTimeout` is a built-in JavaScript function used to delay function execution for a specified time (in milliseconds). ✅ **How to Cancel a Timeout?** We use `clearTimeout(timeoutID)`, where `timeoutID` is the value returned by `setTimeout`. This prevents the function from running if the timeout is cleared before execution. --- # **Approach** I explored **two different approaches** to solve this problem: --- # 🔹 **Approach 1: Using `setTimeout` with Explicit Clear** ```js var cancellable = function(fn, args, t) { let timer = setTimeout(() => { fn(...args); }, t); return () => { clearTimeout(timer); }; }; ``` 📌 **Explanation:** - `setTimeout` schedules function execution after `t` milliseconds. - The returned function (`cancellable`) stores the timeout reference. - If the user calls this function, `clearTimeout(timer)` cancels execution. ✅ **Pros:** - Simple and easy to understand. - Works well for basic timeout cancellations. --- # 🔹 **Approach 2: Passing Arguments Directly to `setTimeout`** ```js var cancellable = function(fn, args, t) { let timer = setTimeout(fn, t, ...args); return () => clearTimeout(timer); }; ``` 📌 **Key Differences:** - Instead of using an arrow function inside `setTimeout`, we pass `fn` directly with arguments. - Reduces function wrapping overhead, making it slightly more efficient. ✅ **Pros:** - More concise than Approach 1. - Uses **native `setTimeout` argument passing**, which improves readability. --- # **Complexity Analysis** - **Time Complexity:** - $$O(1)$$ – `setTimeout` and `clearTimeout` are constant-time operations. - **Space Complexity:** - $$O(1)$$ – We store only a single timeout reference. --- # **Code Implementation** ```js /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timer = setTimeout(fn, t, ...args); return () => clearTimeout(timer); }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15); */ ``` --- # **Important Topics to Learn 📚** - **JavaScript Timers (`setTimeout`, `clearTimeout`)**: Controlling function execution timing. - **Asynchronous Execution**: Handling delayed execution in JavaScript. - **Function Closures**: Returning functions with access to outer variables. - **Higher-Order Functions**: Functions that return other functions (like our cancellable function). --- # 🚀 **Support & Feedback** ✅ If you found this helpful, **please upvote & comment** on my solution! 💬 Let’s discuss alternative solutions & improvements! 🚀
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-shalinipaidimudd-ag4w
IntuitionApproachComplexity Time complexity: Space complexity: Code
ShaliniPaidimuddala
NORMAL
2025-03-25T08:42:35.548593+00:00
2025-03-25T08:42:35.548593+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ const cancellable = function(fn, args, t) { // cancelFn function// const cancelFn = function (){ clearTimeout(timer); }; const timer = setTimeout(()=>{ fn(...args) }, t); return cancelFn ; }; /** * const result = [] * * const fn = (x) => x * 5 * const args = [2], t = 20, cancelT = 50 * * const log = (...argsArr) => { * result.push(fn(...argsArr)) * } * * const cancel = cancellable(fn, args, t); * * setTimeout(() => { * cancel() * console.log(result) // [{"time":20,"returned":10}] * }, cancelT) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-user2274fq-jlmf
IntuitionApproachComplexity Time complexity: Space complexity: Code
user2274fQ
NORMAL
2025-03-22T10:59:15.585758+00:00
2025-03-22T10:59:15.585758+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (...args: JSONValue[]) => void function cancellable(fn: Fn, args: JSONValue[], t: number): Function { const cancelFn = function(){ clearTimeout(timer) } const timer = setTimeout(() =>{ fn(...args) } ,t ) return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['TypeScript']
0
timeout-cancellation
Solution
solution-by-_lou123-ce48
IntuitionMy first thought were to think of how to cancel the timed out process.ApproachMy approach is simple return a function that remembers the unique identif
_lou123
NORMAL
2025-03-12T07:10:49.793020+00:00
2025-03-12T07:10:49.793020+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> My first thought were to think of how to cancel the timed out process. # Approach <!-- Describe your approach to solving the problem. --> My approach is simple return a function that remembers the unique identifier of that timed out process. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> it's quoite - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> Uses not so much memory since it just needs to remember the processes' id # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timeOutId = setTimeout(()=>{fn(...args)},t); return function cancelFn(){ clearTimeout(timeOutId) } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Solution
solution-by-_lou123-vehl
IntuitionMy first thought were to think of how to cancel the timed out process.ApproachMy approach is simple return a function that remembers the unique identif
_lou123
NORMAL
2025-03-12T07:10:46.689245+00:00
2025-03-12T07:10:46.689245+00:00
0
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> My first thought were to think of how to cancel the timed out process. # Approach <!-- Describe your approach to solving the problem. --> My approach is simple return a function that remembers the unique identifier of that timed out process. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> it's quoite - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> Uses not so much memory since it just needs to remember the processes' id # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timeOutId = setTimeout(()=>{fn(...args)},t); return function cancelFn(){ clearTimeout(timeOutId) } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
JavaScript Efficient Solution
javascript-efficient-solution-by-jayanth-el8m
IntuitionApproachComplexity Time complexity: Space complexity: Code
jayanth_br
NORMAL
2025-03-08T04:59:30.620479+00:00
2025-03-08T04:59:30.620479+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function (fn, args, t) { const timeoutId = setTimeout(() => { return fn(...args); }, t); return function cancelFn() { clearTimeout(timeoutId); }; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation solve
timeout-cancellation-solve-by-ariyaneias-ozxp
IntuitionApproachComplexity Time complexity: Space complexity: Code
ariyanEiasin02
NORMAL
2025-03-06T08:47:29.949448+00:00
2025-03-06T08:47:29.949448+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timeout = setTimeout(()=> fn(...args),t) return ()=>{ clearTimeout(timeout) } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
A timeout by any other name would still smell as sweet... unless it’s a memory leak!
a-timeout-by-any-other-name-would-still-hmdf5
IntuitionApproachComplexity Time complexity: Space complexity: Code
ecabigting
NORMAL
2025-03-02T09:04:33.027437+00:00
2025-03-02T09:04:33.027437+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timeOutToCancel = setTimeout(fn,t,...args); return function(){ clearTimeout(timeOutToCancel) } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
timeout-cancellation
timeout-cancellation-by-devmazaharul-w3tl
Code
devmazaharul
NORMAL
2025-02-26T02:27:19.340717+00:00
2025-02-26T02:27:19.340717+00:00
4
false
# Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timeoutId =setTimeout(()=>{ return fn(...args) },t) const cancelFn=()=>{ clearTimeout(timeoutId); } return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-gauravkum2002-j5bg
Approach setTimeoutdelays execution offnwithargsbytmilliseconds. ReturnscancelFn, which: UsesclearTimeout(timeoutId)to cancel the execution if called beforetmil
gauravkum2002
NORMAL
2025-02-22T14:45:43.705673+00:00
2025-02-22T14:45:43.705673+00:00
5
false
# Approach <!-- Describe your approach to solving the problem. --> 1. `setTimeout` delays execution of `fn` with `args` by `t` milliseconds. 2. Returns `cancelFn`, which: - Uses `clearTimeout(timeoutId)` to cancel the execution if called before `t` milliseconds. 3. If `cancelFn` is not called, `fn` executes after `t` milliseconds. # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timeoutId = setTimeout(() => fn(...args), t); return function cancelFn() { clearTimeout(timeoutId); } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Beats 99.89%
beats-9989-by-danilvereschagin-674c
IntuitionApproachComplexity Time complexity: Space complexity: Code
danilvereschagin
NORMAL
2025-02-21T20:42:39.115468+00:00
2025-02-21T20:42:39.115468+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timer = setTimeout(() => { fn(...args); }, t) const cancelFn = function (){ clearTimeout(timer); } return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
[Explanation] Very simple solution using ClearTimeout⌚| 56 ms - Beats 91.67%
explanation-very-simple-solution-using-c-tozb
CodeExplanationProblem DescriptionYou're given: A functionfn. An array of argumentsargsfor the functionfn. A delay timetin milliseconds. Your task is to r
Mathinraj
NORMAL
2025-02-21T09:31:25.105491+00:00
2025-02-21T09:31:25.105491+00:00
3
false
# Code ```javascript [] var cancellable = function(fn, args, t) { const timeout = setTimeout(() => { fn(...args) }, t) return function (){ clearTimeout(timeout) } }; ``` # Explanation ### Problem Description You're given: 1. A function `fn`. 2. An array of arguments `args` for the function `fn`. 3. A delay time `t` in milliseconds. Your task is to return a cancellation function `cancelFn` that: 1. Initially delays the execution of `fn` by `t` milliseconds. 2. If `cancelFn` is invoked before the `t` milliseconds delay, it cancels the execution of `fn`. 3. If `cancelFn` is not invoked within `t` milliseconds, `fn` is executed with `args`. ### Code Explanation Here’s the code : ```javascript [] var cancellable = function(fn, args, t) { const timeout = setTimeout(() => { fn(...args) }, t) return function () { clearTimeout(timeout) } }; ``` - **setTimeout**: This function sets a timer that executes `fn` after `t` milliseconds with the provided arguments `args`. - **clearTimeout**: This function cancels the timer set by `setTimeout` if called before the delay `t`. ### How it Works 1. **Setting the Timeout**: The function `fn` is scheduled to run after `t` milliseconds by using `setTimeout`. 2. **Returning Cancel Function**: The `cancellable` function returns a new function `cancelFn`. 3. **Canceling Execution**: When `cancelFn` is called, it uses `clearTimeout` to cancel the previously scheduled execution of `fn`. ### Examples 1. **Example 1**: - `fn = (x) => x * 5`, `args = [2]`, `t = 20` - `const cancelTimeMs = 50` - `cancelFn` is scheduled after 50ms, which is after `fn` would have executed. - So, `fn(2)` executes at 20ms, returning `10`. 2. **Example 2**: - `fn = (x) => x**2`, `args = [2]`, `t = 100` - `const cancelTimeMs = 50` - `cancelFn` is scheduled after 50ms, which is before `fn` would have executed. - `fn(2)` never executes, so the output is an empty array. 3. **Example 3**: - `fn = (x1, x2) => x1 * x2`, `args = [2, 4]`, `t = 30` - `const cancelTimeMs = 100` - `cancelFn` is scheduled after 100ms, which is after `fn` would have executed. - So, `fn(2, 4)` executes at 30ms, returning `8`. ### Summary The `cancellable` function ensures that `fn` will be executed after `t` milliseconds unless `cancelFn` is called before `t` milliseconds elapses, cancelling the execution.
0
0
['JavaScript']
0
timeout-cancellation
Solution
solution-by-aradhanadevi_jadeja-owxk
Code
Aradhanadevi_Jadeja
NORMAL
2025-02-19T10:50:41.627945+00:00
2025-02-19T10:50:41.627945+00:00
3
false
# Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timer = setTimeout(() => fn(...args), t); return function cancelFn(){ clearTimeout(timer); } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation - 30 Days of JavaScript
timeout-cancellation-30-days-of-javascri-spoo
IntuitionApproachComplexity Time complexity: Space complexity: Code
AleksanderP
NORMAL
2025-02-19T07:38:55.690081+00:00
2025-02-19T07:38:55.690081+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timerId = setTimeout(fn, t, ...args); return function() { clearTimeout(timerId); }; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
LeetCode 2715: Timeout Cancellation - JavaScript Solution 🚀 Easy explanation
leetcode-2715-timeout-cancellation-javas-2ovs
IntuitionThe problem requires us to execute a function after a delay but also provides a way to cancel the execution if needed.To solve this, we can take advant
nagaliyakhushi
NORMAL
2025-02-17T06:13:39.698280+00:00
2025-02-17T06:13:39.698280+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires us to execute a function after a delay but also provides a way to cancel the execution if needed. To solve this, we can take advantage of JavaScript’s **setTimeout()**, which schedules a function to run after a given time. However, we also need a way to stop it before it executes, which can be done using **clearTimeout()**. 💡 Think of it like setting an alarm⏰—if you turn it off before it rings, it never goes off! # Approach <!-- Describe your approach to solving the problem. --> 1. Use **setTimeout()** to delay the execution of fn by t milliseconds. 2. Store the timeout ID returned by **setTimeout()**. 3. Return a cancel function that, when called, will use **clearTimeout()** to prevent fn from running. 4. If cancelFn is called before t milliseconds, the function is never executed. Otherwise, it runs as scheduled. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(1)$$ → We just schedule a timeout and cancel it if needed. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(1)$$ → We only store the timeout ID. # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { //running the function after the t(time) let cancelId = setTimeout(() => fn(...args),t); return function cancelFn(){ //clearing out the time out clearTimeout(cancelId); } }; // An array to store the result of the function executions const result = []; const fn = (x) => x * 5; const args = [2], t = 20, cancelTimeMs = 50; // Recording the start time for performance measurement const start = performance.now(); const log = (...argsArr) => { const diff = Math.floor(performance.now() - start); result.push({"time": diff, "returned": fn(...argsArr)}); } const cancel = cancellable(log, args, t); const maxT = Math.max(t, cancelTimeMs); setTimeout(cancel, cancelTimeMs); setTimeout(() => { console.log(result); // [{"time":20,"returned":10}] }, maxT + 15) ``` # 💡 Key Takeaway: setTimeout allows delaying a function call, and clearTimeout helps prevent its execution if needed. This approach efficiently implements the timeout cancellation mechanism. 🚀
0
0
['JavaScript']
0
timeout-cancellation
The best solution
the-best-solution-by-aslolbek-0a93
IntuitionApproachComplexity Time complexity: Space complexity: Code
Aslolbek
NORMAL
2025-02-13T12:32:22.838256+00:00
2025-02-13T12:32:22.838256+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timer = setTimeout(() => fn(...args), t); return () => clearTimeout(timer); }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Better Explanation of the Problem! – [ beats 94% ]
better-explanation-of-the-problem-beats-fjofg
IntuitionMy first intuition was that I needed another way to explain myself this problem, e.g. using a pizza analogy:Imagine you ordered pizza delivery, and the
Bocya
NORMAL
2025-02-12T19:09:38.694935+00:00
2025-02-12T19:09:38.694935+00:00
4
false
# Intuition My first intuition was that I needed another way to explain myself this problem, e.g. using a pizza analogy: --- Imagine you ordered pizza delivery, and the estimated time of arrival is 30 minutes. However, you have the option to cancel the order before it is prepared. Here is how it maps the problem: - ```fn``` execution is – pizza delivery. - ```t``` (delay) is – 30 minutes waiting time. - ```return cencelFn``` – call the restaurant and cancel the order. - ```cancelTimeMs``` – the time when you **decide** to cancel, so it can be too late or not. 👉🏼 If you cancel **before** 30 minutes, the pizza is **never made**. 👉🏼 If you cancel **after** 30 minutes, the pizza is **already delivered**. --- # Steps 1. Schedule the execution of `fn` after `t` milliseconds using `setTimeout`. 2. Store the `setTimeout` ID in a variable so we can reference it inside `cancelFn` function. 3. Return a `cancelFn` that stops the scheduled execution of `fn(...args)` by clearing `setTimeout` using its ID. # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ const cancellable = function(fn, args, t) { const timerId = setTimeout(() => { fn(...args); }, t); const cancelFn = () => { clearTimeout(timerId); }; return cancelFn; }; ```
0
0
['JavaScript']
0
timeout-cancellation
Simple And Easy To Understand 😎
simple-and-easy-to-understand-by-01anand-2pcw
IntuitionApproachComplexity Time complexity: Space complexity: Code
01AnandKumar
NORMAL
2025-02-05T15:33:14.607155+00:00
2025-02-05T15:33:14.607155+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (...args: JSONValue[]) => void function cancellable(fn: Fn, args: JSONValue[], t: number): Function { const cancelFn = function() { clearTimeout(timer); }; const timer = setTimeout(() => { fn(...args) }, t); return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['TypeScript']
0
timeout-cancellation
clearTimeout || JS || Simple ||
cleartimeout-js-simple-by-ashish_ujjwal-rxds
Code
Ashish_Ujjwal
NORMAL
2025-02-05T10:37:10.003192+00:00
2025-02-05T10:37:10.003192+00:00
3
false
# Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const cancelFn = function(){ clearTimeout(timer); } const timer = setTimeout(()=>{ fn(...args) }, t); return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation | setTimeout() | cleareTimeout()
timeout-cancellation-settimeout-cleareti-mrof
Code
UtkarshRH
NORMAL
2025-02-05T04:32:46.880852+00:00
2025-02-05T04:32:46.880852+00:00
4
false
# Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { cancelFn = function(){ clearTimeout(timer); } const timer = setTimeout(() =>{ fn(...args) },t) return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Easy SetTimeout Solution with a boolean flag
easy-settimeout-solution-with-a-boolean-xq6sp
IntuitionApproachComplexity Time complexity: Space complexity: Code
nipung19
NORMAL
2025-02-04T13:10:05.636069+00:00
2025-02-04T13:10:05.636069+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let stillWaiting = true; let timer = setTimeout(()=>{ stillWaiting = false; return fn(...args); }, t) return function cancelFn(){ if(stillWaiting){ clearTimeout(timer); } } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-nguyenlongdang19-dj5r
IntuitionApproachComplexity Time complexity: Space complexity: Code
nguyenlongdang1999
NORMAL
2025-02-04T07:36:58.770017+00:00
2025-02-04T07:36:58.770017+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (...args: JSONValue[]) => void function cancellable(fn: Fn, args: JSONValue[], t: number): Function { const timeMs = setTimeout(() => fn(...args), t); return () => clearTimeout(timeMs); }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['TypeScript', 'JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-ubaidhabib0-hfg6
IntuitionTo solve this problem, we need a function that can execute another function after a specified delay and can also cancel the execution if needed. This i
UbaidHabib0
NORMAL
2025-02-02T09:56:45.855826+00:00
2025-02-02T09:56:45.855826+00:00
3
false
# Intuition To solve this problem, we need a function that can execute another function after a specified delay and can also cancel the execution if needed. This is useful for scenarios where you might want to schedule a function to run but also have the ability to cancel it before it runs. # Approach 1. Define the cancellable function: This function should take another function fn, an array of arguments args, and a delay time t in milliseconds. 2. Set a timeout: Use setTimeout to schedule the execution of fn with the provided args after t milliseconds. 3. Return a cancel function: Provide a way to cancel the scheduled execution by calling clearTimeout on the created timeout. # Complexity - Time complexity: . $$O(1)$$ The time complexity is constant because setting and clearing a timeout are both constant-time operations. - Space complexity: .$$O(1)$$ The space complexity is also constant because we are only storing a fixed number of variables. # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const cancelFn = function(){ clearTimeout(timer); } const timer = setTimeout(() => { fn(...args); } , t ) return cancelFn; }; const result = []; const fn = (x) => x * 5; const args = [2], t = 20, cancelTimeMs = 50; const start = performance.now(); const log = (...argsArr) => { const diff = Math.floor(performance.now() - start); result.push({"time": diff, "returned": fn(...argsArr)}); } const cancel = cancellable(log, args, t); const maxT = Math.max(t, cancelTimeMs); setTimeout(cancel, cancelTimeMs); setTimeout(() => { console.log(result); // [{"time":20,"returned":10}] }, maxT + 15) ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-pranavdewangan22-uckl
IntuitionApproachComplexity Time complexity: Space complexity: Code
Pranavdewangan22
NORMAL
2025-02-02T04:57:12.284429+00:00
2025-02-02T04:57:12.284429+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timer = setTimeout(() => { fn(...args); }, t); const cancelFunc = function() { clearTimeout(timer); }; return cancelFunc; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
ProphesierC - Timeout Cancellation using Closures
prophesierc-timeout-cancellation-using-c-x6xh
IntuitionThe goal is to create a function that schedules another function to run after a specified time but allows for cancellation before it runs. By using Jav
ProphesierC
NORMAL
2025-02-01T22:41:21.642051+00:00
2025-02-01T22:41:21.642051+00:00
2
false
# Intuition The goal is to create a function that schedules another function to run after a specified time but allows for cancellation before it runs. By using JavaScript's `setTimeout`, we can schedule the function and capture its ID to later cancel the execution if needed. ### Closure Formation: - The inner function (returned by cancellable) forms a closure over the timeoutId variable declared in the outer function (cancellable). This means that even after cancellable has finished executing, the returned function can still access and modify timeoutId. ### Scheduling with setTimeout: - Inside the cancellable function, setTimeout(() => fn(...args), t) schedules the execution of fn with its arguments args after t milliseconds. The setTimeout call returns a timeout ID which is stored in timeoutId. ### Canceling the Timeout: - The returned function uses clearTimeout(timeoutId) to cancel the pending setTimeout operation whenever it is invoked. This prevents fn from executing if the cancellation occurs before the specified time t. # Approach 1. **Schedule Function Execution**: Use `setTimeout` to schedule the execution of the provided function `fn` with its arguments after `t` milliseconds. 2. **Capture Timeout ID**: Store the timeout ID returned by `setTimeout` so it can be used later for cancellation. 3. **Return Cancel Function**: The returned function uses `clearTimeout` with the stored timeout ID to cancel the scheduled execution whenever it is called. This approach leverages closures to keep track of the timeout ID, enabling the canceling mechanism. # Complexity - Time complexity: O(1) Both setTimeout and clearTimeout operations are executed in constant time as they involve simple internal bookkeeping without proportional resource usage relative to input size. - Space Complexity: O(1) The space complexity is constant because only a single timeout ID and the closure over it are stored, regardless of the input size. # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ const cancellable = function(fn, args, t) { const timeoutId = setTimeout(() => { fn(...args); }, t); return function() { clearTimeout(timeoutId); }; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
JS - using setTimeout & clearTimeout functions
js-using-settimeout-cleartimeout-functio-k573
IntuitionApproachComplexity Time complexity: Space complexity: Code
Manmohan_Choudhary
NORMAL
2025-02-01T17:40:41.597150+00:00
2025-02-01T17:40:41.597150+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const cancelFn = function(){ clearTimeout(timer); } const timer = setTimeout(()=>{ fn(...args); },t) return cancelFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Easiset javascript solution
easiset-javascript-solution-by-chris0403-g4tq
IntuitionApproachComplexity Time complexity: Space complexity: Code
chris0403
NORMAL
2025-01-24T06:07:26.173485+00:00
2025-01-24T06:07:26.173485+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] var cancellable = function(fn, args, t) { const timeoutId = setTimeout(() => { fn(...args); }, t); return function() { clearTimeout(timeoutId); }; }; ```
0
0
['JavaScript']
0
timeout-cancellation
Best Way !!!
best-way-by-off_br0wn-oqu9
IntuitionApproachComplexity Time complexity: Space complexity: Code
off_br0wn
NORMAL
2025-01-22T13:10:06.042341+00:00
2025-01-22T13:10:06.042341+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (...args: JSONValue[]) => void function cancellable(fn: Fn, args: JSONValue[], t: number): Function { const setTime = setTimeout(()=>{ fn(...args) },t) const cancelFn = ()=>{ clearTimeout(setTime) } return cancelFn }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['TypeScript']
0
timeout-cancellation
Easy approach
easy-approach-by-vamsi0874-bfxn
IntuitionApproachComplexity Time complexity: Space complexity: Code
vamsi0874
NORMAL
2025-01-21T04:52:46.050531+00:00
2025-01-21T04:52:46.050531+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type Fn = (...args: JSONValue[]) => void; function cancellable(fn: Fn, args: JSONValue[], t: number): Function { // Schedule the function to execute after time `t` const timeoutId = setTimeout(() => fn(...args), t); // Return a cancel function return () => { clearTimeout(timeoutId); // Cancels the scheduled function }; } /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['TypeScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-dltfw5phyl-zbrl
IntuitionApproachComplexity Time complexity: Space complexity: Code
dlTfw5PHyL
NORMAL
2025-01-16T20:51:26.360883+00:00
2025-01-16T20:51:26.360883+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] function cancellable(fn, args, t) { // Timeout ID for the function call let timeoutId; // The cancel function const cancelFn = () => { clearTimeout(timeoutId); // Clear the timeout if cancelFn is called before fn executes }; timeoutId = setTimeout(() => { fn(...args); }, t); return cancelFn; } const fn1 = (x) => x * 5; const cancelFn1 = cancellable(fn1, [2], 20); setTimeout(cancelFn1, 50); const fn2 = (x) => x ** 2; const cancelFn2 = cancellable(fn2, [2], 100); setTimeout(cancelFn2, 50); const fn3 = (x1, x2) => x1 * x2; const cancelFn3 = cancellable(fn3, [2, 4], 30); setTimeout(cancelFn3, 100); ```
0
0
['JavaScript']
0
timeout-cancellation
Easy way to solve (bit tricky)
easy-way-to-solve-bit-tricky-by-rajeskad-ti5g
IntuitionApproachComplexity Time complexity: Space complexity: Code
RAJESKadam
NORMAL
2025-01-08T09:43:29.690812+00:00
2025-01-08T09:43:29.690812+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ function cancellable(fn, args, t) { let timeoutId; // Store the timeout ID let isExecuted = false; // Track whether fn has executed // Schedule the execution of fn timeoutId = setTimeout(() => { isExecuted = true; const result = fn(...args); console.log({ time: t, returned: result }); }, t); // Return the cancel function const cancelFn = () => { if (!isExecuted) { clearTimeout(timeoutId); // Cancel the scheduled fn execution console.log([]); // No execution, return an empty result } }; return cancelFn; } ```
0
0
['JavaScript']
0
timeout-cancellation
2715. Timeout Cancellation
2715-timeout-cancellation-by-g8xd0qpqty-3wbp
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-06T17:34:48.526869+00:00
2025-01-06T17:34:48.526869+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { // Schedule the function to run after 't' milliseconds const timeoutId = setTimeout(() => { fn(...args); }, t); // Return a cancellation function that clears the timeout return function cancel() { clearTimeout(timeoutId); }; }; /** * Example usage: */ const result = []; const fn = (x) => x * 5; const args = [2], t = 20, cancelTimeMs = 50; const start = performance.now(); // Log function that records time and function output const log = (...argsArr) => { const diff = Math.floor(performance.now() - start); result.push({"time": diff, "returned": fn(...argsArr)}); } // Create a cancellable function const cancel = cancellable(log, args, t); // Cancel the function before it executes setTimeout(cancel, cancelTimeMs); // After the max time, log the result const maxT = Math.max(t, cancelTimeMs); setTimeout(() => { console.log(result); // Expected: [{"time": 20, "returned": 10}] }, maxT + 15); ```
0
0
['JavaScript']
0
timeout-cancellation
Easiest Approach 🥕 🥕 🥕
easiest-approach-by-rajasibi-f2tk
IntuitionApproachComplexity Time complexity: Space complexity: Code
RajaSibi
NORMAL
2025-01-06T05:01:36.833940+00:00
2025-01-06T05:01:36.833940+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const val=setTimeout(()=>{ return fn(...args) },t) return()=>clearTimeout(val) }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-nsakshid0702-u7j5
IntuitionApproachComplexity Time complexity: Space complexity: Code
nsakshid0702
NORMAL
2025-01-01T03:05:28.603612+00:00
2025-01-01T03:05:28.603612+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] function cancellable(fn, args, t) { let timeoutId; // To store the setTimeout reference let cancelFn; // The cancel function to be returned // cancelFn will cancel the scheduled function call cancelFn = function () { clearTimeout(timeoutId); // Cancel the timeout }; // Set the function execution to be delayed by 't' milliseconds timeoutId = setTimeout(() => { fn(...args); // Execute the function with the provided arguments }, t); // Return the cancel function return cancelFn; } // Example usage: // Test 1 const cancelTimeMs = 50; const cancelFn1 = cancellable((x) => { console.log("fn executed:", x * 5); }, [2], 20); setTimeout(cancelFn1, cancelTimeMs); // Cancel after 50ms // Test 2 const cancelFn2 = cancellable((x) => { console.log("fn executed:", x ** 2); }, [2], 100); setTimeout(cancelFn2, cancelTimeMs); // Cancel after 50ms // Test 3 const cancelFn3 = cancellable((x1, x2) => { console.log("fn executed:", x1 * x2); }, [2, 4], 30); setTimeout(cancelFn3, 100); // Cancel after 100ms ```
0
0
['JavaScript']
0
timeout-cancellation
simple code beats 99.29%
simple-code-beats-9929-by-utkarsh_7707-9g04
IntuitionApproachComplexity Time complexity: Space complexity: Code
utkarsh_7707
NORMAL
2024-12-31T10:29:28.584897+00:00
2024-12-31T10:29:28.584897+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timer = setTimeout(function(){ fn(...args) },t); let cancellableFn = function() { clearTimeout(timer); } return cancellableFn; }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Simple Solution with explanation of the program and approach to solve the problem step by step
simple-solution-with-explanation-of-the-7dq4a
IntuitionUnderstand the given condition and think the logic to the given problem and the return value.ApproachHear we can create a function that which can clear
Shashankpatelc
NORMAL
2024-12-30T14:59:58.833061+00:00
2024-12-30T14:59:58.833061+00:00
0
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Understand the given condition and think the logic to the given problem and the return value. # Approach <!-- Describe your approach to solving the problem. --> Hear we can create a function that which can clear the timer. # Breakedown of problem - We have a timer `t`, arguments `args` and a function `fn`. - we have to call a `setTimeout()` which execute a `fn`. - We have a another function `cancelFn` which cancel the timer. - If the function `cancelFn` is invoked before the `t` milliseconds it should cancel the `fn` execution. If it is not invoked `fn` should be executed with arguments `args`. - We use `clearTimer` inside the `cancelFn` to clear the timer. # Breakdown of program - Here we have a function called `cancellable` with arguments as `fn` function,`args` arguments for fn function,`t` timer which return a function called `cancelFn`. - `let cancelFn = function(){ clearTimeout(timer) }` it is cancel function which clear the timer `t` using the method `cancleTimer` by passing. - `timer` is variable which store the return value of the `setTimeout(()=>{ fn(...args) },t)`. - `setTimeout(()=>{ fn(...args) },t)` which wit for the `t` milliseconds and execute the `fn` function. - `return cancelFn` which call the `cancelFn` and execute it. # Complexity - Time complexity:O(1) <!-- Add your time complexity here, e.g. $$O(n)$$ --> because it performs a constant amount of work regardless of the size of the input. - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> ecause the function uses a fixed amount of space for the timer and the `cancelFn`. # Code ```javascript [] var cancellable = function(fn, args, t) { let cancelFn = function(){ clearTimeout(timer) } let timer = setTimeout(()=>{ fn(...args) },t) return cancelFn }; ```
0
0
['JavaScript']
0
timeout-cancellation
Simple Solution with explanation of the program and approach to solve the problem step by step
simple-solution-with-explanation-of-the-nxfi4
IntuitionUnderstand the given condition and think the logic to the given problem and the return value.ApproachHear we can create a function that which can clear
Shashankpatelc
NORMAL
2024-12-30T14:59:49.263929+00:00
2024-12-30T14:59:49.263929+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Understand the given condition and think the logic to the given problem and the return value. # Approach <!-- Describe your approach to solving the problem. --> Hear we can create a function that which can clear the timer. # Breakedown of problem - We have a timer `t`, arguments `args` and a function `fn`. - we have to call a `setTimeout()` which execute a `fn`. - We have a another function `cancelFn` which cancel the timer. - If the function `cancelFn` is invoked before the `t` milliseconds it should cancel the `fn` execution. If it is not invoked `fn` should be executed with arguments `args`. - We use `clearTimer` inside the `cancelFn` to clear the timer. # Breakdown of program - Here we have a function called `cancellable` with arguments as `fn` function,`args` arguments for fn function,`t` timer which return a function called `cancelFn`. - `let cancelFn = function(){ clearTimeout(timer) }` it is cancel function which clear the timer `t` using the method `cancleTimer` by passing. - `timer` is variable which store the return value of the `setTimeout(()=>{ fn(...args) },t)`. - `setTimeout(()=>{ fn(...args) },t)` which wit for the `t` milliseconds and execute the `fn` function. - `return cancelFn` which call the `cancelFn` and execute it. # Complexity - Time complexity:O(1) <!-- Add your time complexity here, e.g. $$O(n)$$ --> because it performs a constant amount of work regardless of the size of the input. - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> ecause the function uses a fixed amount of space for the timer and the `cancelFn`. # Code ```javascript [] var cancellable = function(fn, args, t) { let cancelFn = function(){ clearTimeout(timer) } let timer = setTimeout(()=>{ fn(...args) },t) return cancelFn }; ```
0
0
['JavaScript']
0
timeout-cancellation
My hardest question so far, damm!
my-hardest-question-so-far-damm-by-karan-hz6a
IntuitionI won't lie the moment I saw this question, I had a firm believe that somehow I should be able to solve this problem. It was this belief that kept me h
karan-verma108
NORMAL
2024-12-30T01:57:13.780223+00:00
2024-12-30T01:57:13.780223+00:00
3
false
# Intuition I won't lie the moment I saw this question, I had a firm believe that somehow I should be able to solve this problem. It was this belief that kept me hanging on this problem for over 3 days (found the solution on the 4th day, pheww...). # Approach Again I won't lie the descrition really made it difficult to follow a certain approach for me. I tried out varous ways to get it done. Later, I sticked with the current approach. I pretty much got confused about returning the cancelFn. I also had to look for what others did (had to look for solutions yeah, I coundn't figure on my own on the 4th day so I got really frustrated.) Even though I copy pasted one or two solutions, they didn't seem to work at all. I don't know these people also copy pasted someone's solutions or not. Nonetheless, I got a hit out of these solutions, that's for sure.And this is the line that made my code to work : ```javascript [] if (t < cancelTimeMs) { result.push({ time: startTime - cancelTimeMs, returned: fn(...args) }); } ``` # Complexity - Time complexity: O(1) - Space complexity: O(1) # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function (fn, args, t) { const timer = setTimeout(() => { fn(...args); }, t); return function cancelFn() { clearTimeout(timer); }; }; const result = []; const cancelTimeMs = 50; const fn = (x) => x * 5; const t = 20; const args = [2]; const startTime = Math.floor(performance.now()); if (t < cancelTimeMs) { result.push({ time: startTime - cancelTimeMs, returned: fn(...args) }); } const returnedCancelFn = cancellable(fn, args, t); setTimeout(() => { returnedCancelFn(); console.log(result); }, cancelTimeMs); /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Easy Solution || 2 liner
easy-solution-2-liner-by-barevadiyadhava-83fk
Code
barevadiyadhaval1212
NORMAL
2024-12-29T05:26:45.701679+00:00
2024-12-29T05:26:45.701679+00:00
4
false
# Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function (fn, args, t) { let timeout = setTimeout(() => fn(...args), t); return () => clearTimeout(timeout) }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
first naive approach
first-naive-approach-by-user1935qf-7vho
IntuitionApproachComplexity Time complexity: Space complexity: Code
user1935qF
NORMAL
2024-12-28T15:14:22.357983+00:00
2024-12-28T15:14:22.357983+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function (fn, args, t) { cancelToken = setTimeout(() => { fn(...args); }, t); return () => clearTimeout(cancelToken); }; ```
0
0
['JavaScript']
0
timeout-cancellation
# Timeout Cancellation (LeetCode #2715)
timeout-cancellation-leetcode-2715-by-dh-1j8r
IntuitionThe problem requires us to execute a function with a delay and allow its execution to be canceled before the timeout expires. If the cancellation occur
Dheeraj7321
NORMAL
2024-12-22T06:26:52.524164+00:00
2024-12-22T06:26:52.524164+00:00
4
false
# Intuition The problem requires us to execute a function with a delay and allow its execution to be canceled before the timeout expires. If the cancellation occurs before the timeout, the function should not be executed. The challenge is to handle both the function execution and the cancellation mechanism efficiently while ensuring the correct time is captured when the function is invoked. # Approach The approach to solving this problem revolves around using JavaScript's `setTimeout` to handle the delayed execution of the function and `clearTimeout` for cancellation. The `cancellable` function receives a function `fn`, arguments `args`, and a timeout `t`. It sets up a timeout to invoke the function after `t` milliseconds and returns a cancellation function to clear the timeout if invoked before the function is executed. ## Steps: 1. **Setting a Timeout**: Use `setTimeout` to invoke the provided function `fn` with the given arguments `args` after a delay of `t` milliseconds. 2. **Cancellation**: The `cancellable` function returns a `cancelFn` which, when invoked, calls `clearTimeout` to prevent the function from executing if canceled before the timeout. 3. **Time Logging**: Track the time at which the function is executed using `performance.now()`, and log the time of execution and the result. # Complexity ## Time Complexity: - The time complexity is **O(1)** because: - We are only setting a timeout (`setTimeout`) and performing a single function call when the timeout completes. - The cancellation operation (`clearTimeout`) is also constant time. ## Space Complexity: - The space complexity is **O(1)** because we only store a few variables (`timeoutId`, `startTime`, etc.), and no additional data structures are used that grow with input size. # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { let timeoutId; // Create a function to cancel the timeout const cancelFn = () => clearTimeout(timeoutId); // Set a timeout to invoke the function after t milliseconds timeoutId = setTimeout(() => { fn(...args); // Call the function with the provided arguments }, t); return cancelFn; // Return the cancel function to stop the timeout if needed }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Use setTimeout and clearTimeout
use-settimeout-and-cleartimeout-by-roman-o5hu
IntuitionApproachComplexity Time complexity: Space complexity: Code
roman_gravit
NORMAL
2024-12-20T13:44:19.596660+00:00
2024-12-20T13:44:19.596660+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function(fn, args, t) { const timer = setTimeout(() => { return fn(...args); }, t); return function cancelFn() { clearTimeout(timer); } }; /** * const result = []; * * const fn = (x) => x * 5; * const args = [2], t = 20, cancelTimeMs = 50; * * const start = performance.now(); * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)}); * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelTimeMs); * * setTimeout(cancel, cancelTimeMs); * * setTimeout(() => { * console.log(result); // [{"time":20,"returned":10}] * }, maxT + 15) */ ```
0
0
['JavaScript']
0
timeout-cancellation
Two simple lines
two-simple-lines-by-abbasrm-397p
Code
abbasrm
NORMAL
2024-12-18T13:13:43.230869+00:00
2024-12-18T13:13:43.230869+00:00
5
false
# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function (fn, args, t) {\n const timer = setTimeout(fn, t, ...args);\n\n return () => clearTimeout(timer);\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
Easy Solution
easy-solution-by-virendangi123-2xgk
IntuitionApproachComplexity Time complexity: Space complexity: Code
Virendangi123
NORMAL
2024-12-14T15:38:02.233050+00:00
2024-12-14T15:38:02.233050+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n var timeout = setTimeout(() =>\n fn(...args)\n , t)\n var cancelFn = () => clearTimeout(timeout);\n\n return cancelFn; \n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Collection (JS)
timeout-collection-js-by-123malay-c65i
null
123Malay
NORMAL
2024-12-11T06:43:18.735363+00:00
2024-12-11T06:43:18.735363+00:00
2
false
\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nconst cancellable = function(fn, args, t) {\n // cancelFn function//\n const cancelFn = function (){\n clearTimeout(timer);\n };\n const timer = setTimeout(()=>{\n fn(...args)\n }, t);\n return cancelFn ;\n};\n\n\n/**\n * const result = []\n *\n * const fn = (x) => x * 5\n * const args = [2], t = 20, cancelT = 50\n *\n * const log = (...argsArr) => {\n * result.push(fn(...argsArr))\n * }\n * \n * const cancel = cancellable(fn, args, t);\n * \n * setTimeout(() => {\n * cancel()\n * console.log(result) // [{"time":20,"returned":10}]\n * }, cancelT)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
Code 2715. Timeout Cancellation
code-2715-timeout-cancellation-by-thanhm-bpxc
null
thanhmantml99
NORMAL
2024-12-11T03:52:35.493480+00:00
2024-12-11T03:52:35.493480+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timerId = setTimeout(fn,t,...args);\n return ()=>{\n clearTimeout(timerId);\n }\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, c;ancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
cancellable Function
cancellable-function-by-anikaleet-xqs5
null
Anikaleet
NORMAL
2024-12-10T16:21:17.978836+00:00
2024-12-10T16:21:17.978836+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n![jh.JPG](https://assets.leetcode.com/users/images/bbfa50a0-1cc4-487b-bb58-23ed9d3b6848_1733847607.41793.jpeg)\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: o(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timeout = setTimeout(() => {\n fn(...args);\n }, t);\n\n return function() {\n clearTimeout(timeout);\n }\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
Simple Solution ....
simple-solution-by-sreekuttan_n-lw4k
null
SREEKUTTAN_N
NORMAL
2024-12-10T14:18:22.291318+00:00
2024-12-10T14:18:22.291318+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timer=setTimeout(()=>{\n return fn(...args)\n },t)\n\n const cancelFn=()=>{\n clearTimeout(timer)\n }\n return cancelFn\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
Timeout cancellation
timeout-cancellation-by-patra_dinata-vwdj
null
patra_dinata
NORMAL
2024-12-10T13:41:35.189505+00:00
2024-12-10T13:41:35.189505+00:00
1
false
********Bold********# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const cancelTimeout = setTimeout(() => {\n fn(...args)\n }, t)\n return () =>clearTimeout(cancelTimeout)\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
Timeout Cancellation
timeout-cancellation-by-vitalii_baidak-hk0e
null
vitalii_baidak
NORMAL
2024-12-10T09:35:44.361955+00:00
2024-12-10T09:35:44.361955+00:00
4
false
# Code\n```typescript []\ntype JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };\ntype Fn = (...args: JSONValue[]) => void\n\nfunction cancellable(fn: Fn, args: JSONValue[], t: number): Function {\n const timeout = setTimeout(() => fn(...args), t);\n\n return function() {\n clearTimeout(timeout);\n }\n};\n```
0
0
['TypeScript']
0
timeout-cancellation
Basic approach ...!
basic-approach-by-vineeth_v_s-wzh7
null
Vineeth_V_S
NORMAL
2024-12-10T07:23:40.107169+00:00
2024-12-10T07:23:40.107169+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const ref = setTimeout(() => {\n fn(...args)\n },t);\n\n return () => clearTimeout(ref)\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
Solution beat 99%
solution-beat-99-by-truonganletk-4yl6
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
truonganletk
NORMAL
2024-12-08T04:23:24.907028+00:00
2024-12-08T04:23:24.907047+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const timeOut = setTimeout(fn, t, ...args)\n return ()=> clearTimeout(timeOut)\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
運用同步執行先於異步的特性
yun-yong-tong-bu-zhi-xing-xian-yu-yi-bu-esdqp
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
iiijoe
NORMAL
2024-12-07T14:41:46.927727+00:00
2024-12-07T14:41:46.927762+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function (fn, args, t) {\n \n \n let result;\n \n \n let jt = setTimeout(()=>{result = fn(...args)} ,t)\n \n\n return () => {\n \n \n clearTimeout(jt)\n\n return result;\n\n \n };\n};\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
1
timeout-cancellation
JavaScript Easy Solution | Beats 100% Faster | Beginner's Friendly :)
javascript-easy-solution-beats-100-faste-vn31
Code\njavascript []\nconst cancellable = function(fn, args, t) {\n const cancelFn = function (){\n clearTimeout(timer);\n };\n\n const timer = s
Abhishek_Nayak_
NORMAL
2024-11-30T04:20:19.241116+00:00
2024-11-30T04:20:19.241143+00:00
2
false
# Code\n```javascript []\nconst cancellable = function(fn, args, t) {\n const cancelFn = function (){\n clearTimeout(timer);\n };\n\n const timer = setTimeout(()=>{\n fn(...args)\n }, t);\n\n return cancelFn;\n};\n```
0
0
['JavaScript']
0
timeout-cancellation
js easy
js-easy-by-hacker_bablu_123-w4sp
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves creating a cancellable function wrapper that executes a given func
Hacker_Bablu_123
NORMAL
2024-11-29T19:02:01.464644+00:00
2024-11-29T19:02:01.464672+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves creating a cancellable function wrapper that executes a given function fn with specified arguments args after a delay t. The wrapper must also return a cancel function, allowing the timeout to be canceled if invoked before fn is executed.\n\nThe intuition is to use JavaScript\'s setTimeout for the delay and clearTimeout to implement the cancellation logic.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet up the timer: Use setTimeout to schedule the execution of the provided function fn after the delay t with the arguments args.\nCancellation logic: Return a function (cancelfn) that, when invoked, clears the timeout using clearTimeout, preventing fn from being called.\nHandle the timeout ID: Store the ID returned by setTimeout in a variable so it can be accessed by the cancelfn for clearing.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(1)\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const cancelfn =function(){\n clearTimeout(Timer)\n }\n const Timer = setTimeout(()=>{\n fn(...args)\n },t)\n \n return cancelfn\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
js Easy
js-easy-by-hacker_bablu_123-9t20
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires creating a cancellable function, which executes after a delay unle
Hacker_Bablu_123
NORMAL
2024-11-29T18:54:03.859848+00:00
2024-11-29T18:54:03.859878+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires creating a cancellable function, which executes after a delay unless canceled. The intuition revolves around leveraging setTimeout for the delay and clearTimeout to cancel the execution.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitialize the Timer:\n\nUse setTimeout to schedule the execution of the provided function fn after t milliseconds with arguments args.\nReturn a Cancellation Function:\n\nUse clearTimeout within the cancellation function to stop the timer before fn executes.\nEnsure the Timer identifier is in the correct scope so the cancellation function can access and clear it.\nExecution Flow:\n\nCall fn(...args) after the delay t if not canceled.\nAllow cancellation of the timer by calling the returned function.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n const cancelfn =function(){\n clearTimeout(Timer)\n }\n const Timer = setTimeout(()=>{\n fn(...args)\n },t)\n \n return cancelfn\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
JavaScript Solution
javascript-solution-by-mwheeler-dev-4l3s
Code\njavascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nconst cancellable = (fn, args, t) =
MWheeler-Dev
NORMAL
2024-11-19T22:39:51.939352+00:00
2024-11-19T22:39:51.939394+00:00
1
false
# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nconst cancellable = (fn, args, t) => {\n const cancelFn = () => {\n clearTimeout(timer)\n };\n const timer = setTimeout(() => {\n fn(...args)\n }, t);\n return cancelFn;\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
timeout-cancellation
timeout-cancellation-by-jayesh0604-s96f
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
jayesh0604
NORMAL
2024-11-18T17:24:56.549173+00:00
2024-11-18T17:24:56.549222+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n let timeoutId;\n\n timeoutId = setTimeout(() => {\n fn(...args);\n }, t);\n\n return () => {\n clearTimeout(timeoutId);\n };\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
this is how i understood the process
this-is-how-i-understood-the-process-by-0rtlw
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
nik-lc
NORMAL
2024-11-17T10:35:04.786205+00:00
2024-11-17T10:35:04.786226+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n //lets create a setTimeoutfn that will start exicuting (timer starts) upon calling ();\n const setTimerfunction = setTimeout(() => {\n //this the logic needs to exicute after timeout\n fn(...args);//we use spread op(...) to unpack the args and fn exicuted \n },t); //setTimeout takes 2 args this is the amount of time after which to exicute the fn(...args)\n\n //we need to return the stop mechinsum when the cancellable(); is called and if its called before then fn is not exicuted and simply return nothing\n return function(){//declared a anonymous fn\n clearTimeout(setTimerfunction);//cancles the timeout when called\n }\n\n\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
setTimeout clearTimeout
settimeout-cleartimeout-by-abravaciufuk-seju
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
abravaciufuk
NORMAL
2024-11-14T18:19:11.582636+00:00
2024-11-14T18:19:11.582677+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n\n const timeout = setTimeout(() => {\n fn(...args); \n }, t);\n\n return function cancelFn() {\n // if it calls before t, destroy the timeout and just return\n clearTimeout(timeout);\n };\n};\n\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
cancel time JS
cancel-time-js-by-fedwar-q4uf
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Fedwar
NORMAL
2024-11-09T18:02:10.064738+00:00
2024-11-09T18:02:10.064778+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function (fn, args, t) {\n let timerId = setTimeout(() => {\n fn(...args)\n }, t)\n return clearTimeout.bind(null, timerId);\n}\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
timeout-cancellation
easy code
easy-code-by-bhagyalaxmi_palai-9408
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
bhagyalaxmi_palai
NORMAL
2024-11-08T17:59:47.279867+00:00
2024-11-08T17:59:47.279913+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n var timeOut = setTimeout(() => {\n fn(...args);\n },t);\n return() => clearTimeout(timeOut);\n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({"time": diff, "returned": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{"time":20,"returned":10}]\n * }, maxT + 15)\n */\n```
0
0
['JavaScript']
0
maximum-number-of-fish-in-a-grid
BFS/DFS 100% beats Two Detailed Explanation
simple-bfs-detailed-explanation-by-sumee-eglx
IntuitionThe problem involves finding the maximum "fish" that can be collected from connected components in a grid. Each cell in the grid represents the number
Sumeet_Sharma-1
NORMAL
2025-01-28T01:24:43.939854+00:00
2025-01-28T04:23:12.711125+00:00
11,430
false
# Intuition The problem involves finding the maximum "fish" that can be collected from connected components in a grid. Each cell in the grid represents the number of fish, and cells are considered connected if they are adjacent (horizontally or vertically). The task can be broken into identifying connected components and calculating the sum of fish in each. The intuition here is to use a traversal method (like BFS or DFS) to explore connected components starting from every cell containing fish. During the traversal, we keep track of the sum of fish in the current connected component and update the maximum. --- # Approach 1. **Initialization**: - Iterate through each cell in the grid. - If the cell contains fish (value > 0), start a traversal (BFS) to explore the connected component. 2. **Traversal (BFS)**: - Use a queue to manage the cells to explore. - Add the starting cell to the queue and mark it as visited by setting its value to `0`. - For each cell, add its fish value to the current component's sum and enqueue its unvisited neighbors with fish. 3. **Update the Maximum**: - After completing the traversal of a connected component, compare its total fish with the current maximum and update accordingly. 4. **Optimization**: - Instead of using a separate `Visit` matrix, mark cells as visited by setting their value to `0`, reducing memory overhead. --- # Complexity - **Time Complexity**: $$O(m \times n)$$ - Each cell is processed once, either as part of the BFS traversal or skipped because it's water (`0`). - **Space Complexity**: $$O(m \times n)$$ - In the worst case, the queue can hold all the cells in a connected component. ![Screenshot 2025-01-28 065006.png](https://assets.leetcode.com/users/images/00991356-f22d-4c36-828a-1416a30e8320_1738027463.5096087.png) ![9c6f9412-c860-47d6-9a2e-7fcf37ff3321_1686334926.180891.png](https://assets.leetcode.com/users/images/dbe2a095-628a-4078-b40a-0452f3f4f62f_1738027479.6325665.png) --- # Code ```CPP_BFS [] class Solution { public: int findMaxFish(vector<vector<int>>& grid) { int Max = 0; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { if (grid[i][j] > 0) { int C = 0; queue<pair<int, int>> T; T.push({i, j}); while (!T.empty()) { auto [x, y] = T.front(); T.pop(); if (grid[x][y] > 0) { C += grid[x][y]; grid[x][y] = 0; // Mark as visited if (x > 0 && grid[x - 1][y] > 0) T.push({x - 1, y}); if (x + 1 < grid.size() && grid[x + 1][y] > 0) T.push({x + 1, y}); if (y > 0 && grid[x][y - 1] > 0) T.push({x, y - 1}); if (y + 1 < grid[0].size() && grid[x][y + 1] > 0) T.push({x, y + 1}); } } Max = max(Max, C); } } } return Max; } }; ``` ``` CPP_DFS [] class Solution { public: int exploreRegion(int row, int col, vector<vector<int>>& grid) { int rows = grid.size(), cols = grid[0].size(); if (row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] == 0) return 0; int currentFish = grid[row][col]; grid[row][col] = 0; currentFish += exploreRegion(row + 1, col, grid); currentFish += exploreRegion(row - 1, col, grid); currentFish += exploreRegion(row, col + 1, grid); currentFish += exploreRegion(row, col - 1, grid); return currentFish; } int findMaximumFish(vector<vector<int>>& grid) { int rows = grid.size(), cols = grid[0].size(), maxFish = 0; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { if (grid[row][col] != 0) { maxFish = max(maxFish, exploreRegion(row, col, grid)); } } } return maxFish; } }; ```
58
3
['Depth-First Search', 'Breadth-First Search', 'Matrix', 'C++']
7
maximum-number-of-fish-in-a-grid
✔💯 DAY 394 | DFS vs BFS | 100% 0ms | [PYTHON/JAVA/C++] | EXPLAINED | Approach 💫
day-394-dfs-vs-bfs-100-0ms-pythonjavac-e-l80a
Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Intuition & Approach\n Describe your approach to solving the problem. \n##### \u
ManojKumarPatnaik
NORMAL
2023-04-29T16:01:40.655606+00:00
2023-04-29T17:02:11.606898+00:00
4,185
false
# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\n##### \u2022\tWe are given a 2D matrix grid representing land cells and water cells containing fish.\n##### \u2022\tWe need to find the maximum number of fish that can be caught by a fisher starting from any water cell.\n##### \u2022\tWe can start by iterating over all water cells in the grid and using a depth-first search (DFS) to explore all adjacent water cells and calculate the maximum number of fish that can be caught starting from that cell.\n##### \u2022\tIn the DFS, we start with the current water cell and explore all adjacent water cells using a 2D array dr that contains the four possible directions. For each adjacent water cell, we calculate the total number of fish that can be caught starting from the current cell and add it to the maximum number of fish caught so far. We also remove each water cell from the map as we visit it to avoid visiting the same cell twice.\n##### \u2022\tWe keep track of the maximum number of fish caught so far and return it as the answer.\n##### \u2022\tSince we explore each water cell in the grid only once and perform constant time operations for each cell, the time complexity of this solution is O(n), where n is the total number of cells in the grid.\n##### \u2022\tWe can also optimize the solution by using memoization to avoid recomputing the maximum number of fish caught starting from a water cell that has already been visited.\n\n\n\n# Code\n```java []\npublic int findFish(int[][] grid) {\n int n = grid.length;\n int m = grid[0].length;\n int maxFish = 0; // variable to store the maximum number of fish caught\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] > 0) { // if the current cell contains fish\n maxFish = Math.max(maxFish, dfs(i, j, grid, n, m)); // update the maximum number of fish caught\n }\n }\n }\n return maxFish; // return the maximum number of fish caught\n}\n\n// array to store the four possible directions\nprivate final int[] dr = {0, 1, 0, -1, 0};\n\n// function to perform DFS and count the number of fish caught\nint dfs(int i, int j, int[][] grid, int n, int m) {\n int fish = grid[i][j]; // count the number of fish caught in the current cell\n grid[i][j] = 0; // mark the current cell as visited by setting its value to 0\n for(int k = 0; k < 4; k++) { // iterate over the four possible directions\n int nr = i + dr[k], nc = j + dr[k + 1]; // calculate the coordinates of the adjacent cell\n if(nr < n && nr >= 0 && nc < m && nc >= 0 && grid[nr][nc] > 0) { // if the adjacent cell contains fish and is within the grid\n fish += dfs(nr, nc, grid, n, m); // count the number of fish caught in the adjacent cell\n }\n }\n return fish; // return the total number of fish caught\n}\n```\n```c++ []\nint findMaxFish(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int ans = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] > 0) {\n ans = max(ans, dfs(i, j, grid, n, m));\n }\n }\n }\n return ans;\n}\nint dfs(int i, int j, vector<vector<int>>& grid, int n, int m) {\n int f = grid[i][j];\n grid[i][j] = 0;\n int dr[] = {0, 1, 0, -1, 0};\n for(int k = 0; k < 4; k++) {\n int nr = i + dr[k];\n int nc = j + dr[k + 1];\n if(nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] > 0) {\n f += dfs(nr, nc, grid, n, m);\n }\n }\n return f;\n}\n```\n```python []\ndef findMaxFish(self, grid: List[List[int]]) -> int:\n n = len(grid)\n m = len(grid[0])\n ans = 0\n for i in range(n):\n for j in range(m):\n if grid[i][j] > 0:\n ans = max(ans, self.dfs(i, j, grid, n, m))\n return ans\n\ndef dfs(self, i: int, j: int, grid: List[List[int]], n: int, m: int) -> int:\n f = grid[i][j]\n grid[i][j] = 0\n dr = [0, 1, 0, -1, 0]\n for k in range(4):\n nr = i + dr[k]\n nc = j + dr[k + 1]\n if nr >= 0 and nr < n and nc >= 0 and nc < m and grid[nr][nc] > 0:\n f += self.dfs(nr, nc, grid, n, m)\n return f\n```\n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n\n# BFS \n\nWe start by iterating over all water cells in the grid and checking if they contain fish. If a water cell contains fish, we add it to a queue and start the BFS. We also set the value of the current water cell to 0 to mark it as visited.\n\nIn the BFS, we explore all adjacent water cells using two arrays dr and dc that contain the four possible directions. For each adjacent water cell, we add the number of fish it contains to the total number of fish caught so far and mark it as visited by setting its value to 0. We also add it to the queue to explore its adjacent water cells in the next iteration.\n\nAfter the BFS is complete, we update the maximum number of fish caught so far and continue iterating over the remaining water cells.\n\nSince we explore each water cell in the grid only once and perform constant time operations for each cell, the time complexity of this solution is O(n), where n is the total number of cells in the grid.\n```java []\nint findMaxFish[][] grid) {\n int n = grid.length;\n int m = grid[0].length;\n int ans = 0; // variable to store the maximum number of fish caught\n int[] dr = {0, 1, 0, -1}; // array to store the four possible directions\n int[] dc = {1, 0, -1, 0};\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] > 0) { // if the current cell contains fish\n Queue<int[]> q = new LinkedList<>(); // create a queue to perform BFS\n q.offer(new int[]{i, j}); // add the current cell to the queue\n int f = grid[i][j]; // count the number of fish caught in the current cell\n grid[i][j] = 0; // mark the current cell as visited by setting its value to 0\n while(!q.isEmpty()) { // while there are cells in the queue\n int[] curr = q.poll(); // remove the first cell from the queue\n for(int k = 0; k < 4; k++) { // iterate over the four possible directions\n int nr = curr[0] + dr[k]; // calculate the coordinates of the adjacent cell\n int nc = curr[1] + dc[k];\n if(nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] > 0) { // if the adjacent cell contains fish and is within the grid\n f += grid[nr][nc]; // count the number of fish caught in the adjacent cell\n grid[nr][nc] = 0; // mark the adjacent cell as visited by setting its value to 0\n q.offer(new int[]{nr, nc}); // add the adjacent cell to the queue\n }\n }\n }\n ans = Math.max(ans, f); // update the maximum number of fish caught so far\n }\n }\n }\n return ans; // return the maximum number of fish caught\n}\n```\n```c++ []\nclass Solutionpublic:\n int findMaxFish(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int ans = 0;\n vector<int> dr = {0, 1, 0, -1};\n vector<int> dc = {1, 0, -1, 0};\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] > 0) {\n queue<pair<int, int>> q;\n q.push({i, j});\n int f = grid[i][j];\n grid[i][j] = 0;\n while(!q.empty()) {\n auto curr = q.front();\n q.pop();\n for(int k = 0; k < 4; k++) {\n int nr = curr.first + dr[k];\n int nc = curr.second + dc[k];\n if(nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] > 0) {\n f += grid[nr][nc];\n grid[nr][nc] = 0;\n q.push({nr, nc});\n }\n }\n }\n ans = max(ans, f);\n }\n }\n }\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def findMaxFish(self, grid: List[List[int]]) -> int:\n n = len(grid)\n m = len(grid[0])\n ans = 0\n dr = [0, 1, 0, -1]\n dc = [1, 0, -1, 0]\n for i in range(n):\n for j in range(m):\n if grid[i][j] > 0:\n q = deque()\n q.append((i, j))\n f = grid[i][j]\n grid[i][j] = 0\n while q:\n curr = q.popleft()\n for k in range(4):\n nr = curr[0] + dr[k]\n nc = curr[1] + dc[k]\n if nr >= 0 and nr < n and nc >= 0 and nc < m and grid[nr][nc] > 0:\n f += grid[nr][nc]\n grid[nr][nc] = 0\n q.append((nr, nc))\n ans = max(ans, f)\n return ans\n```\n\n![BREUSELEE.webp](https://assets.leetcode.com/users/images/062630f0-ef80-4e74-abdb-302827b99235_1680054012.5054147.webp)\n![image.png](https://assets.leetcode.com/users/images/303fa18d-281d-49f0-87ef-1a018fc9a488_1681355186.0923774.png)\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nhttps://leetcode.com/problems/maximum-number-of-fish-in-a-grid/solutions/3466649/day-394-100-0ms-python-java-c-explained-approach/\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A
50
8
['Depth-First Search', 'Python', 'C++', 'Java', 'Python3']
4
maximum-number-of-fish-in-a-grid
BFS vs DFS vs DSU | Pattern Explained | 100% BEATS
bfs-vs-dfs-vs-dsu-pattern-explained-100-cjech
Problem SimplifiedFind the largest sum of connected cells in a grid where movement is allowed to adjacent (up/down/left/right) cells.When to Use BFS vs DFS vs D
shubham6762
NORMAL
2025-01-28T05:37:51.128059+00:00
2025-01-28T05:37:51.128059+00:00
3,642
false
### **Problem Simplified** Find the largest sum of connected cells in a grid where movement is allowed to adjacent (up/down/left/right) cells. --- ### **When to Use BFS vs DFS vs DSU** | **Algorithm** | **Use Case** | **Pros** | **Cons** | |---------------|-----------------------------------------------|-----------------------------------------------|-----------------------------------------------| | **DFS** | Small grids, connected components, simple sum | Easy to code recursively, minimal code | Stack overflow risk for large grids | | **BFS** | Large grids, shortest path problems | Avoids stack overflow, level-order traversal | Slightly more code for queue management | | **DSU** | Dynamic connectivity, grouping cells | Efficient for merging sets | Harder to track sums, overkill for simple sums | **Why DFS Here?** - Grid size is small (≤10x10). - Directly sum values during traversal. - Minimal code (4-6 lines for DFS). --- ### **Solution Code** ```cpp [] class Solution { public: int m, n, dir[5] = {-1,0,1,0,-1}; int dfs(vector<vector<int>>& grid, int i, int j) { if (i<0 || i>=m || j<0 || j>=n || !grid[i][j]) return 0; int sum = grid[i][j]; grid[i][j] = 0; for (int k=0; k<4; k++) sum += dfs(grid, i+dir[k], j+dir[k+1]); return sum; } int findMaxFish(vector<vector<int>>& grid) { m = grid.size(), n = grid[0].size(); int maxFish = 0; for (int i=0; i<m; i++) for (int j=0; j<n; j++) if (grid[i][j]) maxFish = max(maxFish, dfs(grid,i,j)); return maxFish; } }; ``` ```python [] class Solution: def findMaxFish(self, grid: List[List[int]]) -> int: m, n, dir = len(grid), len(grid[0]), [-1,0,1,0,-1] def dfs(i,j): if i<0 or i>=m or j<0 or j>=n or grid[i][j]==0: return 0 res = grid[i][j] grid[i][j] = 0 for k in range(4): res += dfs(i+dir[k], j+dir[k+1]) return res max_fish = 0 for i in range(m): for j in range(n): if grid[i][j]: max_fish = max(max_fish, dfs(i,j)) return max_fish ``` ```java [] class Solution { int m, n, dir[] = {-1,0,1,0,-1}; private int dfs(int[][] grid, int i, int j) { if (i<0 || i>=m || j<0 || j>=n || grid[i][j]==0) return 0; int sum = grid[i][j]; grid[i][j] = 0; for (int k=0; k<4; k++) sum += dfs(grid, i+dir[k], j+dir[k+1]); return sum; } public int findMaxFish(int[][] grid) { m = grid.length; n = grid[0].length; int maxFish = 0; for (int i=0; i<m; i++) for (int j=0; j<n; j++) if (grid[i][j]>0) maxFish = Math.max(maxFish, dfs(grid,i,j)); return maxFish; } } ``` --- ### **Key Notes** 1. **DFS Direction Array**: `dir = [-1,0,1,0,-1]` simplifies checking 4-directional neighbors. - For each `k` in 0-3: `dir[k]` = row offset, `dir[k+1]` = column offset. - Example: `k=0` → move up (`-1` row), `k=1` → move right (`+1` column). 2. **Time Complexity**: **O(m×n)** – Every cell is processed once. 3. **Space Complexity**: **O(m×n)** – Recursion stack depth in worst case (entire grid is one region). --- ### **Patterns Table** | **Pattern** | **Description** | **Example Problems** | |---------------------------|---------------------------------------------------------------------------------|-------------------------------------------------------------------------------------| | **Connected Components** | Find groups of connected cells (e.g., islands, ponds). | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | | **Flood Fill** | Fill a region with a new value based on adjacency. | [Flood Fill](https://leetcode.com/problems/flood-fill/) | | **Shortest Path** | Find the minimum steps to reach a target cell. | [Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/) | | **Cycle Detection** | Detect cycles in a grid (e.g., repeated paths). | [Detect Cycles in 2D Grid](https://leetcode.com/problems/detect-cycles-in-2d-grid/) | | **Dynamic Connectivity** | Track and merge connected regions dynamically. | [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | | **Boundary Traversal** | Traverse or modify cells on the grid boundary. | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | | **Level-Order Traversal** | Explore cells level by level (BFS). | [Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) | | **Path Counting** | Count the number of valid paths in a grid. | [Unique Paths](https://leetcode.com/problems/unique-paths/) | | **Optimization** | Maximize or minimize a value (e.g., fish, area). | [Maximum Number of Fish in a Grid](https://leetcode.com/problems/maximum-number-of-fish-in-a-grid/) | | **Grouping Cells** | Group cells based on connectivity or properties. | [Count Sub Islands](https://leetcode.com/problems/count-sub-islands/) | --- ### **15 Similar LeetCode Problems** 1. [Max Area of Island (DFS/BFS)](https://leetcode.com/problems/max-area-of-island/) 2. [Number of Islands (DFS/BFS)](https://leetcode.com/problems/number-of-islands/) 3. [Flood Fill (DFS/BFS)](https://leetcode.com/problems/flood-fill/) 4. [Rotting Oranges (BFS)](https://leetcode.com/problems/rotting-oranges/) 5. [Walls and Gates (BFS)](https://leetcode.com/problems/walls-and-gates/) 6. [Surrounded Regions (DFS)](https://leetcode.com/problems/surrounded-regions/) 7. [Island Perimeter (DFS)](https://leetcode.com/problems/island-perimeter/) 8. [Number of Closed Islands (DFS)](https://leetcode.com/problems/number-of-closed-islands/) 9. [Count Sub Islands (DFS/BFS)](https://leetcode.com/problems/count-sub-islands/) 10. [Detonate the Maximum Bombs (DFS/BFS)](https://leetcode.com/problems/detonate-the-maximum-bombs/) 11. [Shortest Path in Binary Matrix (BFS)](https://leetcode.com/problems/shortest-path-in-binary-matrix/) 12. [As Far from Land as Possible (BFS)](https://leetcode.com/problems/as-far-from-land-as-possible/) 13. [Nearest Exit from Entrance (BFS)](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/) 14. [Minimum Knight Moves (BFS)](https://leetcode.com/problems/minimum-knight-moves/) 15. [Detect Cycles in 2D Grid (DFS)](https://leetcode.com/problems/detect-cycles-in-2d-grid/) **Pattern**: All require traversing connected cells in a grid. DFS/BFS for exploration, DSU for dynamic grouping.
41
7
['Depth-First Search', 'Breadth-First Search', 'Union Find', 'Python', 'C++', 'Java']
3
maximum-number-of-fish-in-a-grid
Beats 100% | DFS | Matrix | Solution for LeetCode#2658
dfs-matrix-solution-for-leetcode2658-by-ispw8
IntuitionThe problem seems to be about finding the maximum number of fish that can be caught from a connected area in a 2D grid. The intuition is to use a depth
samir023041
NORMAL
2025-01-28T01:17:52.331063+00:00
2025-01-28T03:05:16.395018+00:00
9,757
false
![image.png](https://assets.leetcode.com/users/images/1c9f7cef-498c-4d51-b8e4-d2e9d56cb201_1738033504.5080497.png) # Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem seems to be about finding the maximum number of fish that can be caught from a connected area in a 2D grid. The intuition is to use a depth-first search (DFS) to explore connected cells with fish and sum up the total fish in each connected component. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate through each cell in the grid. 2. If a cell contains fish (value > 0), start a DFS from that cell. 3. In the DFS: - Mark the current cell as visited. - Add the fish in the current cell to the total. - Recursively explore the four adjacent cells (up, down, left, right). - Return the total fish caught in this connected component. 4. Keep track of the maximum fish caught among all connected components. # Complexity - Time complexity: O(m * n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(m * n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code Option-01 ![image.png](https://assets.leetcode.com/users/images/e63e7f8b-d979-4f65-8dac-26d3fe77abcf_1738027037.2255647.png) ```java [] class Solution { int[][] directions={ {0,1},{0,-1}, {1,0},{-1,0} }; boolean[][] visited; public int findMaxFish(int[][] grid) { int m=grid.length; int n=grid[0].length; int maxFish=0; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(grid[i][j]==0) continue; visited=new boolean[m][n]; maxFish=Math.max(maxFish, dfs(grid, i, j, m, n)); } } return maxFish; } int dfs(int[][] grid, int i, int j, int m, int n){ visited[i][j]=true; int fish=0; if(grid[i][j]==0) return fish; fish+=grid[i][j]; for(int[] dir:directions){ int nr=i+dir[0]; int nc=j+dir[1]; if(nr>=0 && nr<m && nc>=0 && nc<n){ if(!visited[nr][nc]){ fish+=dfs(grid, nr, nc, m, n); } } } return fish; } } ``` # Code Option-02 ![image.png](https://assets.leetcode.com/users/images/81758324-7f61-4253-91e3-dccfe8450201_1738033500.039256.png) ```java [] class Solution { public int findMaxFish(int[][] grid) { int m=grid.length; int n=grid[0].length; int maxFish=0; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(grid[i][j]==0) continue; maxFish=Math.max(maxFish, dfs(grid, i, j, m, n)); } } return maxFish; } int dfs(int[][] grid, int i, int j, int m, int n){ int fish=0; if( i<0 || i>=m || j<0 || j>=n || grid[i][j]==0) return fish; fish+=grid[i][j]; grid[i][j]=0; //Visited fish+=dfs(grid, i, j+1, m, n); fish+=dfs(grid, i, j-1, m, n); fish+=dfs(grid, i+1, j, m, n); fish+=dfs(grid, i-1, j, m, n); return fish; } } ``` # Code Option-03 ![image.png](https://assets.leetcode.com/users/images/7a5ae6fa-62ab-4739-92bb-ac4e7d590958_1738028404.817257.png) ```java [] class Solution { int[][] directions={ {0,1},{0,-1}, {1,0},{-1,0} }; public int findMaxFish(int[][] grid) { int m=grid.length; int n=grid[0].length; int maxFish=0; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(grid[i][j]==0) continue; maxFish=Math.max(maxFish, dfs(grid, i, j, m, n)); } } return maxFish; } int dfs(int[][] grid, int i, int j, int m, int n){ int fish=0; if(grid[i][j]==0) return fish; fish+=grid[i][j]; grid[i][j]=-1; //Visited for(int[] dir:directions){ int nr=i+dir[0]; int nc=j+dir[1]; if(nr>=0 && nr<m && nc>=0 && nc<n){ if(grid[nr][nc]>0){ fish+=dfs(grid, nr, nc, m, n); } } } return fish; } } ``` ```python [] class Solution(object): def findMaxFish(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = [[0,1], [0,-1], [1,0], [-1,0]] m = len(grid) n = len(grid[0]) maxFish = 0 def dfs(i, j, m, n): fish = 0 if grid[i][j] == 0: return fish fish += grid[i][j] grid[i][j] = -1 # Visited for dir in directions: nr = i + dir[0] nc = j + dir[1] if 0 <= nr < m and 0 <= nc < n: if grid[nr][nc] > 0: fish += dfs(nr, nc, m, n) return fish for i in xrange(m): for j in xrange(n): if grid[i][j] == 0: continue maxFish = max(maxFish, dfs(i, j, m, n)) return maxFish ``` ```python [Python3] class Solution: def findMaxFish(self, grid: List[List[int]]) -> int: directions = [[0,1], [0,-1], [1,0], [-1,0]] m = len(grid) n = len(grid[0]) maxFish = 0 def dfs(i: int, j: int, m: int, n: int) -> int: fish = 0 if grid[i][j] == 0: return fish fish += grid[i][j] grid[i][j] = -1 # Visited for dir in directions: nr = i + dir[0] nc = j + dir[1] if 0 <= nr < m and 0 <= nc < n: if grid[nr][nc] > 0: fish += dfs(nr, nc, m, n) return fish for i in range(m): for j in range(n): if grid[i][j] == 0: continue maxFish = max(maxFish, dfs(i, j, m, n)) return maxFish ``` ```cpp [] class Solution { public: vector<vector<int>> directions = {{0,1}, {0,-1}, {1,0}, {-1,0}}; int findMaxFish(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); int maxFish = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == 0) continue; maxFish = max(maxFish, dfs(grid, i, j, m, n)); } } return maxFish; } private: int dfs(vector<vector<int>>& grid, int i, int j, int m, int n){ int fish = 0; if(grid[i][j] == 0) return fish; fish += grid[i][j]; grid[i][j] = -1; // Visited for(const auto& dir : directions){ int nr = i + dir[0]; int nc = j + dir[1]; if(nr >= 0 && nr < m && nc >= 0 && nc < n){ if(grid[nr][nc] > 0){ fish += dfs(grid, nr, nc, m, n); } } } return fish; } }; ```
31
4
['Depth-First Search', 'Python', 'C++', 'Java', 'Python3']
1
maximum-number-of-fish-in-a-grid
[C++, Java] Explained - DFS with node sum || Very simple & easy to understand solution
explained-dfs-with-node-sum-very-simple-qhk0n
Up vote if you like the solution ApproachTrick is to keep traversing the grid from (0,0) with dfs & adding the values of each dfs traverse. Keep adding all non
kreakEmp
NORMAL
2023-04-29T16:03:44.067681+00:00
2025-01-28T02:32:41.296852+00:00
3,796
false
<b> Up vote if you like the solution </b> # Approach Trick is to keep traversing the grid from (0,0) with dfs & adding the values of each dfs traverse. Keep adding all non-zero value traversed is the total no of fish possible on that connected cells. So keep taking the maximum of each dfs run and return it as the answer. Note : Set the node value to 0 once we traversed a node, to avoid retraversing the same node again. # Code ```cpp [] int dir[4][2] = {{1,0}, {0,1}, {-1, 0}, {0,-1}}; int dfs(vector<vector<int>>& grid, int r, int c){ if(r < 0 || c < 0 || r >= grid.size() || c >= grid[0].size() || grid[r][c] == 0) return 0; int res = grid[r][c]; grid[r][c] = 0; for(auto d: dir) res += dfs(grid, r+d[0], c+d[1]); return res; } int findMaxFish(vector<vector<int>>& grid) { int ans = 0; for(int i = 0; i< grid.size(); ++i){ for(int j =0; j < grid[0].size(); ++j) ans = max(ans, dfs(grid, i, j)); } return ans; } ``` ```java [] int[][] dir = new int[][]{{1,0}, {0,1}, {-1,0}, {0,-1}}; int dfs(int[][] grid, int r, int c){ if(r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] == 0) return 0; int res = grid[r][c]; grid[r][c] = 0; for(int[] d: dir) res += dfs(grid, r+d[0], c+d[1]); return res; } int findMaxFish(int[][] grid) { int ans = 0; for(int i = 0; i < grid.length; ++i){ for(int j = 0; j < grid[0].length; ++j) ans = Math.max(ans, dfs(grid, i, j)); } return ans; } ``` <b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon: https://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted
20
1
['C++', 'Java']
7