Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of subarrays forming an Arithmetic Progression (AP)

  • Last Updated : 18 Apr, 2022

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++




// 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);
}

Java




// 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

Python3




# 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

C#




// 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

Javascript




<script>
 
// Javascript implementation of
// the above approach
 
// Function to find the
// total count of subarrays
function calcSubarray(A, N)
{
 
    let count = 0;
 
    // Iterate over each subarray
    for (let i = 0; i < N; i++) {
        for (let j = i + 1; j < N; j++) {
 
            let flag = true;
 
            // Difference between first
            // two terms of subarray
            let comm_diff = A[i + 1] - A[i];
 
            // Iterate over the subarray
            // from i to j
            for (let 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
 
    // Given array
    let A = [ 8, 7, 4, 1, 0 ];
    let N = A.length;
 
    // Function Call
    document.write(calcSubarray(A, N));
 
// This code is contributed by Mayank Tyagi
 
</script>
Output
5

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

Method 2: (Iterate over array only once)

Approach:

The idea is to iterate on the array only once while comparing the difference between adjacent elements and counting the number of elements in each largest subarray for that difference which is stored in the variable t.

For example, consider the array – {1, 2, 3, 7}. Here the largest subarray with difference = 1 is {1, 2, 3}. So here t = 3 and possible subarrays of length at least 2 are {1, 2, 3}, {1, 2} & {2, 3}.  

Similarly, the largest subarray with difference = 4 is {3, 7}. So here t = 2 and possible subarrays of length at least 2 are {3, 7}.

Therefore, total arithmetic subarrays with length at least 2 are 3 + 1 = 4.

To derive possible subarrays for a particular difference we will use the math formula as follows:

(t * (t + 1) ) / 2 – t.  

Let us understand how we got this formula.  

Suppose this is a subarray {1, 2, 3, 4, 5} of some other larger array. Total subarrays with arithmetic difference and length at least 2 using this subarray will be as follows,

{1, 2, 3, 4, 5} = 1

{1, 2, 3, 4}, {2, 3, 4, 5} = 2

{1, 2, 3}, {2, 3, 4}, {3, 4, 5} = 3

{1, 2}, {2, 3}, {3, 4}, {4, 5} = 4

And total number of subarrays = 1 + 2 + 3 + 4  

This is nothing but sum of first (t – 1) consecutive numbers = (t * (t + 1)) / 2 – t.

Similarly, if we had to find arithmetic subarrays with length at least 3, then we will consider the below,

{1, 2, 3, 4, 5} = 1

{1, 2, 3, 4}, {2, 3, 4, 5} = 2

{1, 2, 3}, {2, 3, 4}, {3, 4, 5} = 3

And total number of subarrays in this case = 1 + 2 + 3 for t = 5

The math formula will exclude 4 i.e. (t – 1) and 5 i.e. t from its sum, so formula will be

(t * (t + 1)) / 2 – (t – 1) – (t) = (t * (t + 1)) / 2 – (2 * t) + 1

To count the maximum number of elements in a subarray with a particular difference, we use the variable num.

d variable tracks the difference. d is initialized to the difference between 2nd and 1st element and num will be 1 since for subarrays with 2 elements, the total possible subarrays for that difference will be 1.

Then i is incremented to 1 and we start iterating on the array.

  1. If the difference between adjacent elements matches the difference in variable d, we simply increment the num.
  2. If the difference between adjacent elements does not match the variable d, then we got the subarray with the maximum number of elements for that difference.  
  3. The value of t i.e. maximum number of elements for that difference will be (num + 1). So we use the math formula to add the number of subarrays for length t.
  4. We reset the num to 1 for a new subarray and d to the new difference for next comparison and continue to Step 1.

Below is the implementation of the above approach:

C++




// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the
// total count of subarrays
int calcSubarray(int A[], int N)
{
    // If size of array is smaller than 2,
    // then count will be zero
    if (N < 2) {
        return 0;
    }
 
    int i = 0;
    int num, d, count = 0, t;
 
    // Difference between first two adjacent array elements
    d = A[i + 1] - A[i];
 
    // num stores the total number of elements in a subarray
    // for a particular difference
    num = 1;
 
    // After calculating difference, move to next element
    // and iterate over the array
    i = 1;
    while (i < N - 1) {
 
        // If Difference between adjacent elements is same
        // as d, increment num
        if (A[i + 1] - A[i] == d) {
            num++;
        }
        else {
            // Update the count if number of elements
            // in subarray is greater than 1
            if (num >= 1) {
                t = num + 1;
                count = count + (t * (t + 1)) / 2 - t;
            }
 
            // Reset num
            num = 1;
 
            // Update with new difference
            d = A[i + 1] - A[i];
        }
        i++;
    }
 
    if (num >= 1) {
        t = num + 1;
        count = count + (t * (t + 1)) / 2 - t;
    }
 
    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);
    return 0;
 
    // This code is contributed by Snigdha Patil
}

Python3




# Python implementation of
# the above approach
 
# Function to find the
# total count of subarrays
def calcSubarray(A,N):
 
    # If size of array is smaller than 2,
    # then count will be zero
    if (N < 2):
        return 0
 
    i = 0
    num = 0
    count = 0
    t = 0
 
    # Difference between first two adjacent array elements
    d = A[i + 1] - A[i]
 
    # num stores the total number of elements in a subarray
    # for a particular difference
    num = 1
 
    # After calculating difference, move to next element
    # and iterate over the array
    i = 1
    while (i < N - 1):
 
        # If Difference between adjacent elements is same
        # as d, increment num
        if (A[i + 1] - A[i] == d):
            num += 1
        else:
            # Update the count if number of elements
            # in subarray is greater than 1
            if (num >= 1):
                t = num + 1
                count = count + (t * (t + 1)) // 2 - t
 
            # Reset num
            num = 1
 
            # Update with new difference
            d = A[i + 1] - A[i]
 
        i += 1
 
    if (num >= 1):
        t = num + 1
        count = count + (t * (t + 1)) // 2 - t
 
    return count
 
# Driver Code
 
# Given Array
A = [ 8, 7, 4, 1, 0 ]
N = len(A)
 
# Function Call
print(calcSubarray(A, N))
 
# This code is contributed by Shinjanpatra

Javascript




<script>
 
// JavaScript implementation of
// the above approach
 
// Function to find the
// total count of subarrays
function calcSubarray(A, N)
{
 
    // If size of array is smaller than 2,
    // then count will be zero
    if (N < 2) {
        return 0;
    }
 
    let i = 0;
    let num, d, count = 0, t;
 
    // Difference between first two adjacent array elements
    d = A[i + 1] - A[i];
 
    // num stores the total number of elements in a subarray
    // for a particular difference
    num = 1;
 
    // After calculating difference, move to next element
    // and iterate over the array
    i = 1;
    while (i < N - 1) {
 
        // If Difference between adjacent elements is same
        // as d, increment num
        if (A[i + 1] - A[i] == d) {
            num++;
        }
        else {
            // Update the count if number of elements
            // in subarray is greater than 1
            if (num >= 1) {
                t = num + 1;
                count = count + Math.floor((t * (t + 1)) / 2) - t;
            }
 
            // Reset num
            num = 1;
 
            // Update with new difference
            d = A[i + 1] - A[i];
        }
        i++;
    }
 
    if (num >= 1) {
        t = num + 1;
        count = count + Math.floor((t * (t + 1)) / 2) - t;
    }
 
    return count;
}
 
// Driver Code
 
// Given Array
let A = [ 8, 7, 4, 1, 0 ];
let N = A.length;
 
// Function Call
document.write(calcSubarray(A, N));
 
// This code is contributed by Shinjanpatra
 
</script>
Output
5

Time Complexity: O(N) 

Auxiliary Space: O(1) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!