DEV Community

DPC
DPC

Posted on

Daily JavaScript Challenge #JS-56: Find Missing Number in Arithmetic Sequence

Daily JavaScript Challenge: Find Missing Number in Arithmetic Sequence

Hey fellow developers! 👋 Welcome to today's JavaScript coding challenge. Let's keep those programming skills sharp!

The Challenge

Difficulty: Medium

Topic: Numbers and Sequences

Description

Given an array that represents an arithmetic sequence with exactly one number missing, find the missing number in the sequence. An arithmetic sequence is a sequence of numbers with a constant difference between consecutive terms.

Ready to Begin?

https://www.dpcdev.com/

  1. Fork this challenge
  2. Write your solution
  3. Test it against the provided test cases
  4. Share your approach in the comments below!

Want to Learn More?

Check out the documentation about this topic here: https://en.wikipedia.org/wiki/Arithmetic_progression

Join the Discussion!

  • How did you approach this problem?
  • Did you find any interesting edge cases?
  • What was your biggest learning from this challenge?

Let's learn together! Drop your thoughts and questions in the comments below. 👇


This is part of our Daily JavaScript Challenge series. Follow me for daily programming challenges and let's grow together! 🚀

javascript #programming #coding #dailycodingchallenge #webdev

Top comments (5)

Collapse
 
raskinfe profile image
raskinfe • Edited

Here is my solution for the challenge. Addressing more edge cases and finding multiple missing elements in the sequence. I have not tested it but I assume it should work fine :)

`const findMissingSequence = (arg) => {
if (!Array.isArray(arg)) {
throw new Error("Provided argument is not an array");
}
const length = arg.length;
if (length <= 1) {
return [];
}

const diffs = [];
for (let i = 0; i < length - 1; i++) {
    diffs.push(arg[i + 1] - arg[i]);
}

diffs.sort((a, b) => a - b)

const diff = diffs.shift();

if (diffs.some(d => d % diff !== 0)) {
    throw new Error('Provided argument is not an arithmetic sequence');
}

const missing = [];
let nextSequence = -Infinity;
const sequence = new Set(arg);
let i = 1;
while (true) {
    nextSequence = arg[0] + diff*(i - 1);
    if (nextSequence > arg[length - 1]) { 
      break;
    }

    if (!sequence.has(nextSequence)) {
        missing.push(nextSequence)
    }

    i++
}

return missing;
Enter fullscreen mode Exit fullscreen mode

}`

Collapse
 
dpc profile image
DPC

It works!!

Thanks for sharing your code, we are waiting for you on today's challenge! You can try your code directly there!

Collapse
 
jay7134 profile image
Javed

Its great daily challenge.

Collapse
 
dpc profile image
DPC

See you in the next one! 🙌

Collapse
 
ctsl_db3e83f profile image
Chamod Theekshana

Free programming codes here:
programmingforbegin.blogspot.com/