Skip to content

Added Contains Duplicate #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions L-A/0016 Contains Duplicate/ContainsDuplicate.js
Original file line number Diff line number Diff line change
@@ -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<nums.length;i++){
for(let j=i+1;j<nums.length;j++){
if(Math.abs(nums[i]-nums[j])<=t && (Math.abs(i-j)<=k)){
return true;
}
}
}
return false;
};


// Approach 2
let containsNearbyAlmostDuplicate = (A, K, T, m = {}, abs = Math.abs) => {
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;
};
58 changes: 58 additions & 0 deletions L-A/0016 Contains Duplicate/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# 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.

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.
30 changes: 30 additions & 0 deletions L-I/0012 Promise Time Limit/PromiseTimeLimit.js
Original file line number Diff line number Diff line change
@@ -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
*/
118 changes: 118 additions & 0 deletions L-I/0012 Promise Time Limit/README.md
Original file line number Diff line number Diff line change
@@ -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.