Given an array arr of size N, the task is to find the count of all arithmetic sequences in the array.
Input: arr = [1, 2, 3, 4]
The arithmetic sequences in arr are [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
Input: arr = [1, 3, 5, 6, 7, 8]
The arithmetic sequences in arr are [1, 3, 5], [5, 6, 7], [5, 6, 7, 8] and [6, 7, 8].
- Run two loops and check for each sequence of length at least 3.
- If the sequence is an arithmetic sequence, then increment the answer by 1.
- Finally, return the count of all the arithmetic subarray of size at least 3.
Time Complexity: O(N2)
Efficient approach: We will use a dynamic programming approach to maintain a count of all arithmetic sequences till any position.
- Initialize a variable, res with 0. It will store the count of sequences.
- Initialize a variable, count with 0. It will store the size of the sequence minus 2.
- Increase the value of count if the current element forms an arithmetic sequence else make it zero.
- If the current element L[i] is making an arithmetic sequence with L[i-1] and L[i-2], then the number of arithmetic sequences till the ith iteration is given by:
res = res + count
- Finally, return the res variable.
Below is the implementation of the above approach:
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.