Better Approach in AP series

I have an array of AP series in which one element is missing. I have to print that missing element. [Question Link]
I have use my logic here by finding Common Diff. and iterating the loop.

Anyone can help to optimise it or have better approach?

Can you share question link?

I think O(n) is fine but you may try for binary search on index. Like if you know first term and d of AP then you can know index of each element.

I would suggest finding the sum of n terms of an AP in O(1) and subtracting from array sum as done below-

using namespace std;
#define ll long long
#define mod 1000000007

int main()
int n;
int a[n],i,sum=0;
int d=a[1]-a[0];
int first_Term=a[0];
int num_of_terms=n+1;
int sumOfAP=(num_of_terms / 2) * (2 * first_Term + (n) * d);

1 Like

This is best approach.