Skip to content

Instantly share code, notes, and snippets.

@divmgl
Created December 1, 2015 05:50
Show Gist options
  • Select an option

  • Save divmgl/05f3bc7205a2f6c71a8f to your computer and use it in GitHub Desktop.

Select an option

Save divmgl/05f3bc7205a2f6c71a8f to your computer and use it in GitHub Desktop.
FrogRiverOne JavaScript solution 100%/100%
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
}
@fabio1974
Copy link

fabio1974 commented Jun 12, 2021

function solution(X, A) {
    const m = {}
    let len = 0
    for(let i=0;i<A.length;i++){
        if(X >= A[i] && m[A[i]]==null) {
            m[A[i]] = 1
            len++
        }
        if(len == X)
            return i
    }
    return -1
}

@sarpisik
Copy link

function solution(X, A) {
  let sum = (X * (X + 1)) / 2;
  const hash = {};

  for (let i = 0; i < A.length; i++) {
    const element = A[i];

    if (hash[element]) continue;
    else {
      hash[element] = true;
      sum -= element;

      if (sum === 0) return i;
    }
  }

  return -1;
}

@dimitrisnl
Copy link

dimitrisnl commented Sep 5, 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;

}

@tarikbc
Copy link

tarikbc commented Dec 24, 2021

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