Count of subarrays forming an Arithmetic Progression (AP)

Given an array arr[] of size N, the task is to find the count of subarrays of at least length 2, such that the difference between the consecutive elements of those subarrays remains the same throughout i.e. the elements of the subarray forms an AP. 
Examples:

Input: arr[] = {8, 7, 4, 1, 0} 
Output:
Explanation: 
All subarrays of size greater than 1 which form an AP are [8, 7], [7, 4], [4, 1], [1, 0], [7, 4, 1]

Input: arr[] = {4, 2} 
Output: 1

Approach: The idea is to generate all possible subarrays from the given array and for each subarray, check if the difference between adjacent elements is the same or not for the generated subarrays. Below are the steps:

  1. Iterate over each subarray of length at least 2 using two loops.
  2. Let i be the start index of the subarray and j be the end index of the subarray.
  3. If the difference between every adjacent pair of elements of the array from index i to j is the same then increment the total count.
  4. Otherwise, repeat the above process with the next subarray.

Below is the implementation of the above approach:



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
#include <iostream>
using namespace std;
 
// Function to find the
// total count of subarrays
int calcSubarray(int A[], int N)
{
 
    int count = 0;
 
    // Iterate over each subarray
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
 
            bool flag = true;
 
            // Difference between first
            // two terms of subarray
            int comm_diff = A[i + 1] - A[i];
 
            // Iterate over the subarray
            // from i to j
            for (int k = i; k < j; k++) {
 
                // Check if the difference
                // of all adjacent elements
                // is same
                if (A[k + 1] - A[k] == comm_diff) {
                    continue;
                }
                else {
                    flag = false;
                    break;
                }
            }
 
            if (flag) {
                count++;
            }
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    // Given array
    int A[5] = { 8, 7, 4, 1, 0 };
    int N = sizeof(A) / sizeof(int);
 
    // Function Call
    cout << calcSubarray(A, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of
// the above approach
import java.util.*;
class GFG{
 
// Function to find the
// total count of subarrays
static int calcSubarray(int A[],
                        int N)
{
  int count = 0;
 
  // Iterate over each subarray
  for (int i = 0; i < N; i++)
  {
    for (int j = i + 1; j < N; j++)
    {
      boolean flag = true;
 
      // Difference between first
      // two terms of subarray
      int comm_diff = A[i + 1] - A[i];
 
      // Iterate over the subarray
      // from i to j
      for (int k = i; k < j; k++)
      {
        // Check if the difference
        // of all adjacent elements
        // is same
        if (A[k + 1] - A[k] == comm_diff)
        {
          continue;
        }
        else
        {
          flag = false;
          break;
        }
      }
 
      if (flag)
      {
        count++;
      }
    }
  }
 
  return count;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array
  int []A = {8, 7, 4, 1, 0};
  int N = A.length;
 
  // Function Call
  System.out.print(calcSubarray(A, N));
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of
# the above approach
 
# Function to find the
# total count of subarrays
def calcSubarray(A, N):
 
    count = 0
 
    # Iterate over each subarray
    for i in range(N):
        for j in range(i + 1, N):
            flag = True
 
            # Difference between first
            # two terms of subarray
            comm_diff = A[i + 1] - A[i]
 
            # Iterate over the subarray
            # from i to j
            for k in range(i, j):
 
                # Check if the difference
                # of all adjacent elements
                # is same
                if (A[k + 1] - A[k] == comm_diff):
                    continue
                else:
                    flag = False
                    break
                     
            if (flag):
                count += 1
                 
    return count
 
# Driver Code
if __name__ == '__main__':
 
    # Given array
    A = [ 8, 7, 4, 1, 0 ]
    N = len(A)
 
    # Function call
    print(calcSubarray(A, N))
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of
// the above approach
using System;
class GFG{
 
// Function to find the
// total count of subarrays
static int calcSubarray(int []A,
                        int N)
{
  int count = 0;
 
  // Iterate over each subarray
  for (int i = 0; i < N; i++)
  {
    for (int j = i + 1; j < N; j++)
    {
      bool flag = true;
 
      // Difference between first
      // two terms of subarray
      int comm_diff = A[i + 1] - A[i];
 
      // Iterate over the subarray
      // from i to j
      for (int k = i; k < j; k++)
      {
        // Check if the difference
        // of all adjacent elements
        // is same
        if (A[k + 1] - A[k] == comm_diff)
        {
          continue;
        }
        else
        {
          flag = false;
          break;
        }
      }
 
      if (flag)
      {
        count++;
      }
    }
  }
 
  return count;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array
  int []A = {8, 7, 4, 1, 0};
  int N = A.Length;
 
  // Function Call
  Console.Write(calcSubarray(A, N));
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output: 

5






Time Complexity: O(N3
Auxiliary Space: O(1) 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.