From 6cb3c99a146bd2304fcdf9cd16ad7ea952457785 Mon Sep 17 00:00:00 2001 From: himanshukoshti Date: Thu, 12 Oct 2023 09:46:43 +0530 Subject: [PATCH 1/3] Added Contains Duplicate --- .../ContainsDuplicate.js | 40 +++++++++++++ L-A/0016 Contains Duplicate/README.md | 58 +++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 L-A/0016 Contains Duplicate/ContainsDuplicate.js create mode 100644 L-A/0016 Contains Duplicate/README.md diff --git a/L-A/0016 Contains Duplicate/ContainsDuplicate.js b/L-A/0016 Contains Duplicate/ContainsDuplicate.js new file mode 100644 index 0000000..598d53a --- /dev/null +++ b/L-A/0016 Contains Duplicate/ContainsDuplicate.js @@ -0,0 +1,40 @@ +// Approach 1: Brute Force +/** + * @param {number[]} nums + * @param {number} k + * @param {number} t + * @return {boolean} + */ +var containsNearbyAlmostDuplicate = function(nums, k, t) { + for(let i=0;i { + let N = A.length; + if (N < 2) + return false; + let bucket = x => T ? Math.floor(x / T) : Math.floor(x / (T + 1)); // ⭐️ +1 to avoid division by 0 when T == 0 + let ok = (i, j) => m[j] != undefined && abs(m[j] - A[i]) <= T; + for (let i = 0; i < N; ++i) { + // 1. check each j-th bucket for case 1 || case 2 || case 3 + let j = bucket(A[i]); + if (ok(i, j - 1) || ok(i, j) || ok(i, j + 1)) // (πŸ‘ˆ adjacent bucket to-the-left || 🎯 same bucket || adjacent bucket to-the-right πŸ‘‰) + return true; + // 2. slide window πŸ‘‰ + m[j] = A[i]; // βœ… add current value A[i] onto the window by mapping A[i] to the j-th bucket + if (0 <= i - K) { + let end = bucket(A[i - K]); // 🚫 remove end value A[i - K] from window by removing mapping A[i - K] to end-th bucket which "fell off the end" of window of size K + delete m[end]; + } + } + return false; +}; \ No newline at end of file diff --git a/L-A/0016 Contains Duplicate/README.md b/L-A/0016 Contains Duplicate/README.md new file mode 100644 index 0000000..3b0b27e --- /dev/null +++ b/L-A/0016 Contains Duplicate/README.md @@ -0,0 +1,58 @@ +# Longest Valid Parentheses +[LeetCode Problem]https://leetcode.com/problems/contains-duplicate-iii/description/ + +You are given an integer array nums and two integers indexDiff and valueDiff. + +Find a pair of indices (i, j) such that: +1. i != j, +2. abs(i - j) <= indexDiff. +3. abs(nums[i] - nums[j]) <= valueDiff, and + +Return true if such pair exists or false otherwise. + +## Example 1 +``` +Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 +Output: true +Explanation: We can choose (i, j) = (0, 3). +We satisfy the three conditions: +i != j --> 0 != 3 +abs(i - j) <= indexDiff --> abs(0 - 3) <= 3 +abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0 +``` + +## Example 2: +``` +Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 +Output: false +Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. +``` + +### Constraints: +```javascript +2 <= nums.length <= 105 +-109 <= nums[i] <= 109 +1 <= indexDiff <= nums.length +0 <= valueDiff <= 109 +``` + +## Approach 1: +1. Run a loop for every element nums[i] of the given array. +2. Inside this loop again run a for loop and traverse all the elements from j=i+1 to j=i+k and compare its value to the nums[i]. + (i) If nums[j]==nums[i] then return true. As we have found an element. +3. Finally when no duplicate element is found then return false before exiting the function. + +## Approach 2: +1. Create a Hash Set for storing k previous elements. +2. Traverse for every element nums[i] of the given array in a loop. + (i) Check if hash set already contains nums[i] or not. If nums[i] is present in the set ( i.e. duplicate element is present at a distance less than equal to k ), then return true. Else add nums[i] to the set. + (ii) If the size of the set becomes greater than k then remove the last visited element (nums[i-k]) from the set. +3. Finally when no duplicate element is found then return false before exiting the function. + +## Problem Added By +- [himanshukoshti](https://github.com/himanshukoshti) + +## Contributing +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. + +Please make sure to update tests as appropriate. \ No newline at end of file From 8c9e5c6ae71b58e1917a4c5cf86892bd69133f40 Mon Sep 17 00:00:00 2001 From: Himanshu Koshti <89205070+himanshukoshti@users.noreply.github.com> Date: Thu, 12 Oct 2023 09:53:16 +0530 Subject: [PATCH 2/3] Update README.md --- L-A/0016 Contains Duplicate/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/L-A/0016 Contains Duplicate/README.md b/L-A/0016 Contains Duplicate/README.md index 3b0b27e..208926b 100644 --- a/L-A/0016 Contains Duplicate/README.md +++ b/L-A/0016 Contains Duplicate/README.md @@ -1,4 +1,4 @@ -# Longest Valid Parentheses +# Contains Duplicate [LeetCode Problem]https://leetcode.com/problems/contains-duplicate-iii/description/ You are given an integer array nums and two integers indexDiff and valueDiff. @@ -55,4 +55,4 @@ Explanation: After trying all the possible pairs (i, j), we cannot satisfy the t ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. -Please make sure to update tests as appropriate. \ No newline at end of file +Please make sure to update tests as appropriate. From 0df4e7e76da34d8b006dd9c2cd3b7e85016d502b Mon Sep 17 00:00:00 2001 From: himanshukoshti Date: Thu, 12 Oct 2023 10:04:54 +0530 Subject: [PATCH 3/3] Added Promise Time Limit --- L-A/0016 Contains Duplicate/README.md | 2 +- .../PromiseTimeLimit.js | 30 +++++ L-I/0012 Promise Time Limit/README.md | 118 ++++++++++++++++++ 3 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 L-I/0012 Promise Time Limit/PromiseTimeLimit.js create mode 100644 L-I/0012 Promise Time Limit/README.md diff --git a/L-A/0016 Contains Duplicate/README.md b/L-A/0016 Contains Duplicate/README.md index 3b0b27e..af2e7da 100644 --- a/L-A/0016 Contains Duplicate/README.md +++ b/L-A/0016 Contains Duplicate/README.md @@ -1,4 +1,4 @@ -# Longest Valid Parentheses +# Contains Duplicate [LeetCode Problem]https://leetcode.com/problems/contains-duplicate-iii/description/ You are given an integer array nums and two integers indexDiff and valueDiff. diff --git a/L-I/0012 Promise Time Limit/PromiseTimeLimit.js b/L-I/0012 Promise Time Limit/PromiseTimeLimit.js new file mode 100644 index 0000000..75fa780 --- /dev/null +++ b/L-I/0012 Promise Time Limit/PromiseTimeLimit.js @@ -0,0 +1,30 @@ +/** + * @param {Function} fn + * @param {number} t + * @return {Function} + */ +var timeLimit = function (fn, t) { + return async function (...args) { + return new Promise((delayresolve, reject) => { + const timeoutId = setTimeout(() => { + clearTimeout(timeoutId); + reject("Time Limit Exceeded"); + }, t); + + fn(...args) + .then((result) => { + clearTimeout(timeoutId); + delayresolve(result); + }) + .catch((error) => { + clearTimeout(timeoutId); + reject(error); + }); + }); + }; +}; + +/** + * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100); + * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms + */ \ No newline at end of file diff --git a/L-I/0012 Promise Time Limit/README.md b/L-I/0012 Promise Time Limit/README.md new file mode 100644 index 0000000..e56de1c --- /dev/null +++ b/L-I/0012 Promise Time Limit/README.md @@ -0,0 +1,118 @@ +# Promise Time Limit +[LeetCode Problem]https://leetcode.com/problems/promise-time-limit/ + +Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. fn takes arguments provided to the time limited function. + +The time limited function should follow these rules: + +1. If the fn completes within the time limit of t milliseconds, the time limited function should resolve with the result. +2. If the execution of the fn exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded". + +## Example 1 +``` +Input: +fn = async (n) => { + await new Promise(res => setTimeout(res, 100)); + return n * n; +} +inputs = [5] +t = 50 +Output: {"rejected":"Time Limit Exceeded","time":50} +Explanation: +const limited = timeLimit(fn, t) +const start = performance.now() +let result; +try { + const res = await limited(...inputs) + result = {"resolved": res, "time": Math.floor(performance.now() - start)}; +} catch (err) { + result = {"rejected": err, "time": Math.floor(performance.now() - start)}; +} +console.log(result) // Output + +The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached. +``` + +## Example 2: +``` +Input: +fn = async (n) => { + await new Promise(res => setTimeout(res, 100)); + return n * n; +} +inputs = [5] +t = 150 +Output: {"resolved":25,"time":100} +Explanation: +The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached. +``` + +## Example 3: +``` +Input: +fn = async (a, b) => { + await new Promise(res => setTimeout(res, 120)); + return a + b; +} +inputs = [5,10] +t = 150 +Output: {"resolved":15,"time":120} +Explanation: +​​​​The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached. +``` + +## Example 4: +``` +Input: +fn = async () => { + throw "Error"; +} +inputs = [] +t = 1000 +Output: {"rejected":"Error","time":0} +Explanation: +The function immediately throws an error. +``` + +### Constraints: +```javascript +0 <= inputs.length <= 10 +0 <= t <= 1000 +fn returns a promise +``` + +## Approach 1: +1. Run a loop for every element nums[i] of the given array. +2. Inside this loop again run a for loop and traverse all the elements from j=i+1 to j=i+k and compare its value to the nums[i]. + (i) If nums[j]==nums[i] then return true. As we have found an element. +3. Finally when no duplicate element is found then return false before exiting the function. + +## Approach 2: +1. Create a Hash Set for storing k previous elements. +2. Traverse for every element nums[i] of the given array in a loop. + (i) Check if hash set already contains nums[i] or not. If nums[i] is present in the set ( i.e. duplicate element is present at a distance less than equal to k ), then return true. Else add nums[i] to the set. + (ii) If the size of the set becomes greater than k then remove the last visited element (nums[i-k]) from the set. +3. Finally when no duplicate element is found then return false before exiting the function. + +## Intuition: +We can use a combination of Promise, setTimeout, and async/await to implement the time-limited function. By setting a timeout using setTimeout, we can enforce the time limit and reject the promise if it exceeds the specified duration. + +## Approach: +1. Create a wrapper function that takes the original function fn and the time limit t as parameters. +2. Within the wrapper function, return an async function that accepts any number of arguments using the spread operator ...args. +3. Inside the async function, create a new Promise to handle the asynchronous execution. +4. Use setTimeout to set a timer with the time limit t. If the timer expires before the promise is resolved, reject the promise with the string "Time Limit Exceeded". +5. Call the original function fn with the provided arguments ...args and await its completion. +6. If the function completes before the time limit, resolve the promise with the result. +7. Return the promise from the async function. + +### Time Complexity: O(fn) +### Space Complexity: O(1) + +## Problem Added By +- [himanshukoshti](https://github.com/himanshukoshti) + +## Contributing +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. + +Please make sure to update tests as appropriate. \ No newline at end of file