# javascript – Minimum number of jumps required to reach end of array

This is based on this question: Minimum number of jumps required

It seems that the OP got it quite wrong, and I was curious if my thought process was alright and since it is a different language I wanted to link it to the OP for inspiration.

But I welcome any points you want to make.

Here is the specification (bold words were added for clarity as opposed to the original):

Given an array of non-negative integers where each element represents the max number of steps that can be made forward from that element. The task is to find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cannot move through that element. Return -1 if there is no way to reach the end.

Here is the jaffascript implementation. I believe it is O(n) in time and O(1) in space.

``````function minJumps(a)
{
let jumps = 0;
for (let i = 0; i < a.length; ++i)
{
const reach = i + a(i)
++jumps
if (reach >= a.length) {
return jumps
}
let max = reach;
for (let j = i + 1; j <= reach; ++j)
{
if (j + a(j) > max) {
max = j + a(j)
}
}

if (max <= reach) {
return -1
}

i = max - 1
++jumps;
}
return jumps;
}
``````

And here are some tests:

``````function test(a, expect) {
const result = minJumps(a)
console.log(a, '->', result)
if (result !== expect) {
console.error('Failed, expected: ', expect)
}
}

console.log('------------------------------------------')
test((), 0)
test((1), 1)
test((0), -1)
test((1, 1), 2)
test((1, 1, 1), 3)
test((2, 10, 1, 1, 1, 1), 2)
test((2, 2, 0, 1, 1), 4)
test((2, 1, 0, 4, 5), -1)
test((1, 4, 3, 2, 6, 7), 3)
test((1, 3, 5, 8, 9, 2, 6, 2, 6, 8, 9, 10, 4, 7, 10), 4)
test((1, 3, 5, 8, 9, 2, 6, 2, 6, 8, 9), 3)
test((5, 1, 3, 8, 4, 0), 2)
test((0, 0, 0), -1)
``````