Created
December 1, 2015 05:50
-
-
Save divmgl/05f3bc7205a2f6c71a8f to your computer and use it in GitHub Desktop.
FrogRiverOne JavaScript solution 100%/100%
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function solution(X, A) { | |
| if (A.length === 1) { // If the array is one element | |
| // And if its first item is 1 as well as the value to search for, | |
| // the frog doesn't need to move | |
| if (A[0] === 1 && X === 1) return 0; | |
| // If not, it's impossible to go anywhere | |
| else return -1; | |
| } | |
| var i = -1, // Counter | |
| sum = 0, // Comparison sum | |
| Y = (X * (X+1)) / 2, // Sum of 1..X | |
| f = []; // Found elements | |
| do { // Start searching | |
| i++; // Increase the counter | |
| // If we've already found the element, continue | |
| if (f[A[i]]) continue; | |
| // If we haven't found the element, mark it | |
| f[A[i]] = true; | |
| // Add to the comparison sum that we will be using | |
| // to determine whether the frog will have been | |
| // able to cross successfully by this point and then | |
| // compare it | |
| sum += A[i]; | |
| if (sum === Y) break; | |
| } while (i < A.length) // If the counter is over the length, we didn't find it | |
| // If we reached this point and this conditional is true, | |
| // we didn't find the number. | |
| if (i === A.length) return -1; | |
| return i; // Return how long it took | |
| } |
sarpisik
commented
Jul 27, 2021
Here's mine.
function solution(target, array) {
const positionDict = new Set();
let minSec = 0;
for (let second=0; second <= array.length - 1; second ++){
const position = array[second];
if (positionDict.has(position)){
continue;
}
minSec = Math.max(minSec, second);
positionDict.add(position)
}
return positionDict.size === target ? minSec : -1;
}Here's my solution, using the findIndex method which already satisfies the -1 request when no solution is found.
function solution(X, A){
const set = new Set()
return A.findIndex((el, i) => {
set.add(el)
return set.size === X
})
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment