- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Missing Number In Arithmetic Progression using C++
Suppose we have an array that represents elements of arithmetic progression in order. One element is missing. We have to find the missing element. So if arr = [2, 4, 8, 10, 12, 14], output is 6, as 6 is missing.
Using binary search, we can solve this problem. We will go to the middle element, then check whether the difference between the middle and next to the middle is the same as diff or not. If not, then the missing element is present between indices mid and mid + 1. If the middle element is the n/2th element in the AP, then the missing element lies in the right half, otherwise to the left half.
Example (C++)
#include <iostream> using namespace std; #define INT_MAX 999999 class Progression { public: int missingUtil(int arr[], int left, int right, int diff) { if (right <= left) return INT_MAX; int mid = left + (right - left) / 2; if (arr[mid + 1] - arr[mid] != diff) return (arr[mid] + diff); if (mid > 0 && arr[mid] - arr[mid - 1] != diff) return (arr[mid - 1] + diff); if (arr[mid] == arr[0] + mid * diff) return missingUtil(arr, mid + 1, right, diff); return missingUtil(arr, left, mid - 1, diff); } int missingElement(int arr[], int n) { int diff = (arr[n - 1] - arr[0]) / n; return missingUtil(arr, 0, n - 1, diff); } }; int main() { Progression pg; int arr[] = {2, 4, 8, 10, 12, 14}; int n = sizeof(arr) / sizeof(arr[0]); cout << "The missing element is: " << pg.missingElement(arr, n)<<endl; }
Input
[2,4,8,10,12,14]
Output
The missing element is: 6
- Related Articles
- Find the missing number in Arithmetic Progression in C++
- Finding the missing number in an arithmetic progression sequence in JavaScript
- Find the missing number in Geometric Progression in C++
- What is arithmetic progression?
- Count of AP (Arithmetic Progression) Subsequences in an array in C++
- C Program for N-th term of Arithmetic Progression series
- C program to find the sum of arithmetic progression series
- Convert given array to Arithmetic Progression by adding an element in C++
- Arithmetic Number in C++
- Find the one missing number in range using C++
- Removing a Number from Array to make It Geometric Progression using C++
- Program to check we can make arithmetic progression from sequence in Python
- Find the only missing number in a sorted array using C++
- Find the repeating and the missing number using two equations in C++
- JavaScript code to find nth term of a series - Arithmetic Progression (AP)

Advertisements