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: 5
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:
- Iterate over each subarray of length at least 2 using two loops.
- Let i be the start index of the subarray and j be the end index of the subarray.
- 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.
- Otherwise, repeat the above process with the next subarray.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int calcSubarray( int A[], int N)
{
int count = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
bool flag = true ;
int comm_diff = A[i + 1] - A[i];
for ( int k = i; k < j; k++) {
if (A[k + 1] - A[k] == comm_diff) {
continue ;
}
else {
flag = false ;
break ;
}
}
if (flag) {
count++;
}
}
}
return count;
}
int main()
{
int A[5] = { 8, 7, 4, 1, 0 };
int N = sizeof (A) / sizeof ( int );
cout << calcSubarray(A, N);
}
|
Java
import java.util.*;
class GFG{
static int calcSubarray( int A[],
int N)
{
int count = 0 ;
for ( int i = 0 ; i < N; i++)
{
for ( int j = i + 1 ; j < N; j++)
{
boolean flag = true ;
int comm_diff = A[i + 1 ] - A[i];
for ( int k = i; k < j; k++)
{
if (A[k + 1 ] - A[k] == comm_diff)
{
continue ;
}
else
{
flag = false ;
break ;
}
}
if (flag)
{
count++;
}
}
}
return count;
}
public static void main(String[] args)
{
int []A = { 8 , 7 , 4 , 1 , 0 };
int N = A.length;
System.out.print(calcSubarray(A, N));
}
}
|
Python3
def calcSubarray(A, N):
count = 0
for i in range (N):
for j in range (i + 1 , N):
flag = True
comm_diff = A[i + 1 ] - A[i]
for k in range (i, j):
if (A[k + 1 ] - A[k] = = comm_diff):
continue
else :
flag = False
break
if (flag):
count + = 1
return count
if __name__ = = '__main__' :
A = [ 8 , 7 , 4 , 1 , 0 ]
N = len (A)
print (calcSubarray(A, N))
|
C#
using System;
class GFG{
static int calcSubarray( int []A,
int N)
{
int count = 0;
for ( int i = 0; i < N; i++)
{
for ( int j = i + 1; j < N; j++)
{
bool flag = true ;
int comm_diff = A[i + 1] - A[i];
for ( int k = i; k < j; k++)
{
if (A[k + 1] - A[k] == comm_diff)
{
continue ;
}
else
{
flag = false ;
break ;
}
}
if (flag)
{
count++;
}
}
}
return count;
}
public static void Main(String[] args)
{
int []A = {8, 7, 4, 1, 0};
int N = A.Length;
Console.Write(calcSubarray(A, N));
}
}
|
Javascript
<script>
function calcSubarray(A, N)
{
let count = 0;
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
let flag = true ;
let comm_diff = A[i + 1] - A[i];
for (let k = i; k < j; k++) {
if (A[k + 1] - A[k] == comm_diff) {
continue ;
}
else {
flag = false ;
break ;
}
}
if (flag) {
count++;
}
}
}
return count;
}
let A = [ 8, 7, 4, 1, 0 ];
let N = A.length;
document.write(calcSubarray(A, N));
</script>
|
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.
- If the difference between adjacent elements matches the difference in variable d, we simply increment the num.
- 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.
- 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.
- 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++
#include <bits/stdc++.h>
using namespace std;
int calcSubarray( int A[], int N)
{
if (N < 2) {
return 0;
}
int i = 0;
int num, d, count = 0, t;
d = A[i + 1] - A[i];
num = 1;
i = 1;
while (i < N - 1) {
if (A[i + 1] - A[i] == d) {
num++;
}
else {
if (num >= 1) {
t = num + 1;
count = count + (t * (t + 1)) / 2 - t;
}
num = 1;
d = A[i + 1] - A[i];
}
i++;
}
if (num >= 1) {
t = num + 1;
count = count + (t * (t + 1)) / 2 - t;
}
return count;
}
int main()
{
int A[5] = { 8, 7, 4, 1, 0 };
int N = sizeof (A) / sizeof ( int );
cout << calcSubarray(A, N);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int calcSubarray( int A[], int N)
{
if (N < 2 ) {
return 0 ;
}
int i = 0 ;
int num, d, count = 0 , t;
d = A[i + 1 ] - A[i];
num = 1 ;
i = 1 ;
while (i < N - 1 ) {
if (A[i + 1 ] - A[i] == d) {
num++;
}
else {
if (num >= 1 ) {
t = num + 1 ;
count = count + (t * (t + 1 )) / 2 - t;
}
num = 1 ;
d = A[i + 1 ] - A[i];
}
i++;
}
if (num >= 1 ) {
t = num + 1 ;
count = count + (t * (t + 1 )) / 2 - t;
}
return count;
}
public static void main(String[] args)
{
int A[] = { 8 , 7 , 4 , 1 , 0 };
int N = A.length;
System.out.println(calcSubarray(A, N));
}
}
|
Python3
def calcSubarray(A,N):
if (N < 2 ):
return 0
i = 0
num = 0
count = 0
t = 0
d = A[i + 1 ] - A[i]
num = 1
i = 1
while (i < N - 1 ):
if (A[i + 1 ] - A[i] = = d):
num + = 1
else :
if (num > = 1 ):
t = num + 1
count = count + (t * (t + 1 )) / / 2 - t
num = 1
d = A[i + 1 ] - A[i]
i + = 1
if (num > = 1 ):
t = num + 1
count = count + (t * (t + 1 )) / / 2 - t
return count
A = [ 8 , 7 , 4 , 1 , 0 ]
N = len (A)
print (calcSubarray(A, N))
|
C#
using System;
class Gfg{
static int calcSubarray( int []A, int N)
{
if (N < 2) {
return 0;
}
int i = 0;
int num, d, count = 0, t;
d = A[i + 1] - A[i];
num = 1;
i = 1;
while (i < N - 1) {
if (A[i + 1] - A[i] == d) {
num++;
}
else {
if (num >= 1) {
t = num + 1;
count = count + (t * (t + 1)) / 2 - t;
}
num = 1;
d = A[i + 1] - A[i];
}
i++;
}
if (num >= 1) {
t = num + 1;
count = count + (t * (t + 1)) / 2 - t;
}
return count;
}
public static void Main(String[] args)
{
int []A = { 8, 7, 4, 1, 0 };
int N = A.Length;
Console.Write(calcSubarray(A, N));
}
}
|
Javascript
<script>
function calcSubarray(A, N)
{
if (N < 2) {
return 0;
}
let i = 0;
let num, d, count = 0, t;
d = A[i + 1] - A[i];
num = 1;
i = 1;
while (i < N - 1) {
if (A[i + 1] - A[i] == d) {
num++;
}
else {
if (num >= 1) {
t = num + 1;
count = count + Math.floor((t * (t + 1)) / 2) - t;
}
num = 1;
d = A[i + 1] - A[i];
}
i++;
}
if (num >= 1) {
t = num + 1;
count = count + Math.floor((t * (t + 1)) / 2) - t;
}
return count;
}
let A = [ 8, 7, 4, 1, 0 ];
let N = A.length;
document.write(calcSubarray(A, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)