The Frog River One problem states that a frog can only jump from one side to the other of the river when leaves are placed at each “lane” on the river.
I built another array to keep track of the positions where the leaves have fallen already. This array only has X elements, although the initial array can have a lot more.
Each time when a position gets marked the first time, I incremented the sum of the distance the frog can move currently by one.
When the sum reaches X (the width of the river) I can return that moment as the solution. If this never happens, I returned -1.
Here is the code with O(n) complexity.
Solution:
function solution(X, A) {
let B = Array(X).fill(0)
let sum = 0
for (let i = 0; i < A.length; i++) {
if (A[i] <= X){
if (B[A[i]-1] === 0) {
B[A[i]-1] = 1;
sum += 1;
if (sum === X){
return i
}
}
}
}
return (-1)
}
You can also find the report here.