Skip to content

How to Find the Missing Term in an Arithmetic Progression in Javascript

The challenge

An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers that have been given to you. The rest of the given series is the same as the original AP. Find the missing term.

You have to write a function that receives a list, list size will always be at least 3 numbers. The missing term will never be the first or last one.


findMissing([1, 3, 5, 9, 11]) == 7
Code language: JavaScript (javascript)

The solution in Javascript

Option 1:

var findMissing = function (l) { return ((l[]+l[l.length-1])*(l.length+1))/2-(l.reduce((a,b)=>a+b)) }
Code language: JavaScript (javascript)

Option 2:

var findMissing = function (list) { let delta = (list[list.length - 1] - list[])/list.length; return list.find( (el,ind) => el !== ind*delta + list[]) - delta; }
Code language: JavaScript (javascript)

Option 3:

var findMissing = function (list) { var listLen = list.length; var iter = (list[listLen-1]-list[])/listLen; for(i = ; i < listLen; i++){ var next = list[i] + iter if(next != list[i+1]){ return next; } } }
Code language: JavaScript (javascript)

Test cases to validate our solution

for (let i = ;i < 10;++i) { fixture.random (1+i*5,) ; fixture.random (1+i*5,10) ; fixture.random (1+i*5,100) ; fixture.random (1+i*5,1000) ; fixture.random (1+i*5,10000) ; fixture.random (1+i*5,100000) ; }
Code language: JavaScript (javascript)

See also  [Solved] export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x