Count the Arithmetic sequences in the Array of size at least 3 - GeeksforGeeks

18 Aug, 2021
Given an array arr[] of size N, the task is to find the count of all arithmetic sequences in the array. 
Examples: 
Input: arr = [1, 2, 3, 4] Output: 3 Explanation: 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] Output: 4 Explanation: The arithmetic sequences in arr are [1, 3, 5], [5, 6, 7], [5, 6, 7, 8] and [6, 7, 8].
Naive approach:  
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:  
C++
Java
Python3
C#
Javascript
// C++ program to find all arithmetic// sequences of size atleast 3 #include <bits/stdc++.h>using namespace std; // Function to find all arithmetic// sequences of size atleast 3int numberOfArithmeticSequences(int L[], int N){     // If array size is less than 3    if (N <= 2)        return 0;     // Finding arithmetic subarray length    int count = 0;     // To store all arithmetic subarray    // of length at least 3    int res = 0;     for (int i = 2; i < N; ++i) {         // Check if current element makes        // arithmetic sequence with        // previous two elements        if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) {            ++count;        }         // Begin with a new element for        // new arithmetic sequences        else {            count = 0;        }         // Accumulate result in till i.        res += count;    }     // Return final count    return res;} // Driver codeint main(){     int L[] = { 1, 3, 5, 6, 7, 8 };    int N = sizeof(L) / sizeof(L[0]);     // Function to find arithmetic sequences    cout << numberOfArithmeticSequences(L, N);     return 0;}
// Java program to find all arithmetic// sequences of size atleast 3 class GFG{  // Function to find all arithmetic// sequences of size atleast 3static int numberOfArithmeticSequences(int L[], int N){      // If array size is less than 3    if (N <= 2)        return 0;      // Finding arithmetic subarray length    int count = 0;      // To store all arithmetic subarray    // of length at least 3    int res = 0;      for (int i = 2; i < N; ++i) {         // Check if current element makes        // arithmetic sequence with        // previous two elements        if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) {            ++count;        }          // Begin with a new element for        // new arithmetic sequences        else {            count = 0;        }          // Accumulate result in till i.        res += count;    }      // Return final count    return res;}  // Driver codepublic static void main(String[] args){      int L[] = { 1, 3, 5, 6, 7, 8 };    int N = L.length;      // Function to find arithmetic sequences    System.out.print(numberOfArithmeticSequences(L, N));  }} // This code contributed by sapnasingh4991
# Python3 program to find all arithmetic# sequences of size atleast 3 # Function to find all arithmetic# sequences of size atleast 3def numberOfArithmeticSequences(L, N) :     # If array size is less than 3    if (N <= 2) :        return 0     # Finding arithmetic subarray length    count = 0     # To store all arithmetic subarray    # of length at least 3    res = 0     for i in range(2,N):         # Check if current element makes        # arithmetic sequence with        # previous two elements        if ( (L[i] - L[i - 1]) == (L[i - 1] - L[i - 2])) :            count += 1         # Begin with a new element for        # new arithmetic sequences        else :            count = 0         # Accumulate result in till i.        res += count      # Return final count    return res # Driver code L = [ 1, 3, 5, 6, 7, 8 ]N = len(L) # Function to find arithmetic sequencesprint(numberOfArithmeticSequences(L, N)) # This code is contributed by Sanjit_Prasad
// C# program to find all arithmetic// sequences of size atleast 3using System; class GFG{ // Function to find all arithmetic// sequences of size atleast 3static int numberOfArithmeticSequences(int []L,                                       int N){     // If array size is less than 3    if (N <= 2)        return 0;     // Finding arithmetic subarray length    int count = 0;     // To store all arithmetic subarray    // of length at least 3    int res = 0;     for(int i = 2; i < N; ++i)    {                // Check if current element makes       // arithmetic sequence with       // previous two elements       if (L[i] - L[i - 1] ==           L[i - 1] - L[i - 2])       {           ++count;       }               // Begin with a new element for       // new arithmetic sequences       else       {           count = 0;       }               // Accumulate result in till i.       res += count;    }         // Return readonly count    return res;} // Driver codepublic static void Main(String[] args){    int []L = { 1, 3, 5, 6, 7, 8 };    int N = L.Length;     // Function to find arithmetic sequences    Console.Write(numberOfArithmeticSequences(L, N));}} // This code is contributed by amal kumar choubey
<script>//Javascript program to find all arithmetic// sequences of size atleast 3  // Function to find all arithmetic// sequences of size atleast 3function numberOfArithmeticSequences( L, N){     // If array size is less than 3    if (N <= 2)        return 0;     // Finding arithmetic subarray length    var count = 0;     // To store all arithmetic subarray    // of length at least 3    var res = 0;     for (var i = 2; i < N; ++i) {         // Check if current element makes        // arithmetic sequence with        // previous two elements        if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) {            ++count;        }         // Begin with a new element for        // new arithmetic sequences        else {            count = 0;        }         // Accumulate result in till i.        res += count;    }     // Return final count    return res;} var L = [ 1, 3, 5, 6, 7, 8 ];    var N = L.length; // Function to find arithmetic sequences document.write(numberOfArithmeticSequences(L, N));     // This code contributed by SoumikMondal</script>
4
 
Time Complexity: O(N) 
Sanjit_Prasad
sapnasingh4991
Amal Kumar Choubey
SoumikMondal
arorakashish0911
arithmetic progression
series
Arrays
Dynamic Programming
Mathematical
Pattern Searching
Arrays
Dynamic Programming
Mathematical
series
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Bellman–Ford Algorithm | DP-23
Longest Common Subsequence | DP-4
Floyd Warshall Algorithm | DP-16