Skip to content
Related Articles

Related Articles

Queries to check if array elements from indices [L, R] forms an Arithmetic Progression or not
  • Last Updated : 29 Apr, 2021

Given an array arr[] consisting of N integers and an array Q[][2] consisting of M queries of the form {L, R}, the task for each query is to check if array elements over the range [L, R] forms an Arithmetic Progression or not. If found to be true, print “Yes”. Otherwise, print “No”.

Examples:

Input: arr[] = {1, 3, 5, 7, 6, 5, 4, 1}, Q[][] = {{0, 3}, {3, 4}, {2, 4}}
Output:
Yes
Yes
No
Explanation: 
Query 1: The elements of the array over the range [0, 3] are {1, 3, 5, 7} which forms an arithmetic series with a common difference of 2. Hence, print “Yes”.
Query 2: The elements of the array over the range [3, 4 are {7, 6} which forms an arithmetic series with a common difference of -1. Hence, print “Yes”.
Query 3: The elements of the array over the range [2, 4 are {5, 7, 6}, which does not form an arithmetic series. Hence, print “Yes”.

Input: arr[] = {1, 2}, Q[][] = {{0, 0}, {0, 1}, {0, 1}}
Output:
Yes
Yes
Yes

Naive Approach: The simplest approach to solve the problem is to traverse the given array over the range [L, R] for each query and check if the common difference between all the adjacent elements is the same or not. If the difference is the same, then print “Yes”. Otherwise, print “No”



Time Complexity: O(N*M)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized based on the following observations:

  • The idea is to precompute the longest length of the subarray forming an AP starting from any index i for every ith element of the array in an auxiliary array say dp[] using the Two Pointer Algorithm.
  • For a given range [L, R], if the value of dp[L] is greater than or equal to (R – L), then the range will always form an AP as (R – L) is the current range of elements and dp[L] stores the length of the longest subarray forming AP from index L, then the subarray length must be smaller than dp[L].

Follow the steps below to solve the problem:

  • Initialize an array say dp[] to store the length of the longest subarray starting from each index for each element at that index.
  • Iterate over the range [0, N] using the variable i and perform the following steps:
    • Initialize a variable say j as (i + 1) to store the last index array forming Arithmetic Progression from index i.
    • Increment the value of j until (j + 1 < N) and (arr[j] – arr[j – 1]) is same as (arr[i + 1] – arr[i]).
    • Iterate over the range [i, j – 1] using the variable, say K, and update the value of dp[K] as (j – K).
    • Update the value of i as j.
  • Traverse the given array of queries Q[] and for each query {L, R} if the value of dp[L] is greater than or equal to (R – L), then print “Yes”. Otherwise, print “No”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the given range
// of queries form an AP or not in the
// given array arr[]
void findAPSequence(int arr[], int N,
                    int Q[][2], int M)
{
    // Stores length of the longest
    // subarray forming AP for every
    // array element
    int dp[N + 5] = { 0 };
 
    // Iterate over the range [0, N]
    for (int i = 0; i + 1 < N;) {
 
        // Stores the index of the last
        // element of forming AP
        int j = i + 1;
 
        // Iterate until the element at
        // index (j, j + 1) forms AP
        while (j + 1 < N
               && arr[j + 1] - arr[j]
                      == arr[i + 1] - arr[i])
 
            // Increment j by 1
            j++;
 
        // Traverse the current subarray
        // over the range [i, j - 1]
        for (int k = i; k < j; k++) {
 
            // Update the length of the
            // longest subarray at index k
            dp[k] = j - k;
        }
 
        // Update the value of i
        i = j;
    }
 
    // Traverse the given queries
    for (int i = 0; i < M; i++) {
 
        // Print the result
        if (dp[Q[i][0]]
            >= Q[i][1] - Q[i][0]) {
            cout << "Yes" << endl;
        }
 
        // Otherwise
        else {
            cout << "No" << endl;
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 5, 7, 6, 5, 4, 1 };
    int Q[][2] = { { 0, 3 }, { 3, 4 }, { 2, 4 } };
    int N = sizeof(arr) / sizeof(arr[0]);
    int M = sizeof(Q) / sizeof(Q[0]);
 
    findAPSequence(arr, N, Q, M);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check if the given range
// of queries form an AP or not in the
// given array arr[]
static void findAPSequence(int arr[], int N,
                           int Q[][], int M)
{
     
    // Stores length of the longest
    // subarray forming AP for every
    // array element
    int dp[] = new int[N + 5];
 
    // Iterate over the range [0, N]
    for(int i = 0; i + 1 < N;)
    {
         
        // Stores the index of the last
        // element of forming AP
        int j = i + 1;
 
        // Iterate until the element at
        // index (j, j + 1) forms AP
        while (j + 1 < N && arr[j + 1] - arr[j] ==
                            arr[i + 1] - arr[i])
 
            // Increment j by 1
            j++;
 
        // Traverse the current subarray
        // over the range [i, j - 1]
        for(int k = i; k < j; k++)
        {
             
            // Update the length of the
            // longest subarray at index k
            dp[k] = j - k;
        }
 
        // Update the value of i
        i = j;
    }
 
    // Traverse the given queries
    for(int i = 0; i < M; i++)
    {
         
        // Print the result
        if (dp[Q[i][0]] >= Q[i][1] - Q[i][0])
        {
            System.out.println("Yes");
        }
 
        // Otherwise
        else
        {
            System.out.println("No");
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 3, 5, 7, 6, 5, 4, 1 };
    int Q[][] = { { 0, 3 }, { 3, 4 }, { 2, 4 } };
    int N = arr.length;
    int M = Q.length;
 
    findAPSequence(arr, N, Q, M);
}
}
 
// This code is contributed by Kingash

Python3




# Python3 program for the above approach
 
# Function to check if the given range
# of queries form an AP or not in the
# given array arr[]
def findAPSequence(arr, N, Q, M):
 
    # Stores length of the longest
    # subarray forming AP for every
    # array element
    dp = [0] * (N + 5)
 
    # Iterate over the range [0, N]
    i = 0
     
    while i + 1 < N:
         
        # Stores the index of the last
        # element of forming AP
        j = i + 1
 
        # Iterate until the element at
        # index (j, j + 1) forms AP
        while (j + 1 < N and
           arr[j + 1] - arr[j] ==
           arr[i + 1] - arr[i]):
 
            # Increment j by 1
            j += 1
 
        # Traverse the current subarray
        # over the range [i, j - 1]
        for k in range(i, j):
 
            # Update the length of the
            # longest subarray at index k
            dp[k] = j - k
 
        # Update the value of i
        i = j
 
    # Traverse the given queries
    for i in range(M):
 
        # Print the result
        if (dp[Q[i][0]] >= Q[i][1] - Q[i][0]):
            print("Yes")
 
        # Otherwise
        else:
            print("No")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 1, 3, 5, 7, 6, 5, 4, 1 ]
    Q = [ [ 0, 3 ], [ 3, 4 ], [ 2, 4 ] ]
    N = len(arr)
    M = len(Q)
 
    findAPSequence(arr, N, Q, M)
 
# This code is contributed by ukasp

C#




// C# code for above approach
using System;
 
public class GFG
{
   
    // Function to check if the given range
// of queries form an AP or not in the
// given array arr[]
static void findAPSequence(int[] arr, int N,
                           int[, ] Q, int M)
{
     
    // Stores length of the longest
    // subarray forming AP for every
    // array element
    int[] dp = new int[N + 5];
 
    // Iterate over the range [0, N]
    for(int i = 0; i + 1 < N;)
    {
         
        // Stores the index of the last
        // element of forming AP
        int j = i + 1;
 
        // Iterate until the element at
        // index (j, j + 1) forms AP
        while (j + 1 < N && arr[j + 1] - arr[j] ==
                            arr[i + 1] - arr[i])
 
            // Increment j by 1
            j++;
 
        // Traverse the current subarray
        // over the range [i, j - 1]
        for(int k = i; k < j; k++)
        {
             
            // Update the length of the
            // longest subarray at index k
            dp[k] = j - k;
        }
 
        // Update the value of i
        i = j;
    }
 
    // Traverse the given queries
    for(int i = 0; i < M; i++)
    {
         
        // Print the result
        if (dp[Q[i, 0]] >= Q[i, 1] - Q[i, 0])
        {
            Console.WriteLine("Yes");
        }
 
        // Otherwise
        else
        {
            Console.WriteLine("No");
        }
    }
}
 
    static public void Main (){
      int[] arr = { 1, 3, 5, 7, 6, 5, 4, 1 };
    int[, ] Q = { { 0, 3 }, { 3, 4 }, { 2, 4 } };
    int N = arr.Length;
    int M = Q.GetLength(0);
 
    findAPSequence(arr, N, Q, M);
    }
}
 
// This code is contributed by offbeat

Javascript




<script>
// javascript program for the above approach
    // Function to check if the given range
    // of queries form an AP or not in the
    // given array arr
    function findAPSequence(arr , N , Q , M) {
 
        // Stores length of the longest
        // subarray forming AP for every
        // array element
        var dp = Array(N + 5).fill(0);
 
        // Iterate over the range [0, N]
        for (i = 0; i + 1 < N;) {
 
            // Stores the index of the last
            // element of forming AP
            var j = i + 1;
 
            // Iterate until the element at
            // index (j, j + 1) forms AP
            while (j + 1 < N && arr[j + 1] - arr[j] == arr[i + 1] - arr[i])
 
                // Increment j by 1
                j++;
 
            // Traverse the current subarray
            // over the range [i, j - 1]
            for (k = i; k < j; k++) {
 
                // Update the length of the
                // longest subarray at index k
                dp[k] = j - k;
            }
 
            // Update the value of i
            i = j;
        }
 
        // Traverse the given queries
        for (i = 0; i < M; i++) {
 
            // Prvar the result
            if (dp[Q[i][0]] >= Q[i][1] - Q[i][0]) {
                document.write("Yes <br/>");
            }
 
            // Otherwise
            else {
                document.write("No <br/>");
            }
        }
    }
 
    // Driver Code
     
        var arr = [ 1, 3, 5, 7, 6, 5, 4, 1 ];
        var Q = [ [ 0, 3 ], [ 3, 4 ], [ 2, 4 ] ];
        var N = arr.length;
        var M = Q.length;
 
        findAPSequence(arr, N, Q, M);
 
// This code contributed by umadevi9616
</script>
Output: 
Yes
Yes
No

 

Time Complexity: O(N + M)
Auxiliary Space: 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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :