Skip to content
Related Articles

Related Articles

Find elements in Array whose positions forms Arithmetic Progression

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 23 May, 2022

Given an array A[] of N integers. Consider an integer num such that num occurs in the array A[] and all the positions of num, sorted in increasing order forms an arithmetic progression. The task is to print all such pairs of num along with the common difference of the arithmetic progressions they form.

Examples :

Input: N = 8, A = {1, 2, 1, 3, 1, 2, 1, 5}
Output: {1, 2}, {2, 4}, {3, 0}, {5, 0}
Explanation: Positions at which 1 occurs are: 0, 2, 4, 6 
It can be easily seen all the positions have same difference between consecutive elements (i.e. 2). 
Hence, positions of 1 forms arithmetic progression with common difference 2. 
Similarly, all positions of 2 forms arithmetic progression with common difference 4. 
And, 3 and 5 are present once only. 
According to the definition of arithmetic progression (or A.P.), single element sequences are also A.P. with common difference 0.

Input: N = 1, A = {1}
Output: {1, 0}

 

Approach: The idea to solve the problem is by using Hashing.

Follow the steps to solve the problem:

  • Create a map having integer as key and vector of integers as value of key.
  • Traverse the array and store all positions of each element present in array into the map.
  • Iterate through the map and check if all the positions of the current element in the map forms A.P.
  • If so, insert that element along with the common difference into the answer.
  • Else, continue to iterate through the map

Below is the implementation for the above approach:

C++




// C++ code for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all elements
// in given array whose positions forms
// arithmetic progression
void printAP(int N, int A[])
{
 
    // Declaring a hash table(or map)
    // to store positions of all elements
    unordered_map<int, vector<int> > pos;
 
    // Storing positions of
    // array elements in map
    for (int i = 0; i < N; i++) {
        pos[A[i]].push_back(i);
    }
 
    // Declaring a map to store answer
    // i.e. key - value pair of element
    // with their positions forming A.P.
    // and their common difference
    map<int, int> ans;
 
    // Iterating through the map "pos"
    for (auto x : pos) {
 
        // If current element is present
        // only at 1 position, then simply
        // insert the element in answer
        // with common difference = 0
        if (x.second.size() == 1) {
            ans[x.first] = 0;
        }
 
        // If current element is present
        // at more than one positions,
        // then check if all the
        // positions are at same difference
        else {
            bool flag = 1;
 
            // Storing the difference of
            // first two positions in
            // variable "diff"
            int diff = x.second[1] - x.second[0];
 
            // Declaring "prev" to store
            // previous position of
            // current element
            int prev = x.second[1];
 
            //"curr" stores the
            // Current position of the element
            int curr;
 
            // Iterating through all the
            // positions of the current element
            // and checking id they are in A.P.
            for (auto it = 2;
                 it < x.second.size(); it++) {
                curr = x.second[it];
                if (curr - prev != diff) {
                    flag = 0;
                    break;
                }
                prev = x.second[it];
            }
 
            // If all positions of current
            // element are in A.P.
            // Insert it into answer with
            // common difference as "diff"
            if (flag == 1) {
                ans[x.first] = diff;
            }
        }
    }
 
    // Printing the answer
    for (auto it : ans) {
        cout << it.first << " "
             << it.second << endl;
    }
}
 
// Driver Code
int main()
{
    int N = 8;
    int A[] = { 1, 2, 1, 3, 1, 2, 1, 5 };
    printAP(N, A);
}

Python3




## Function to print all elements
## in given array whose positions forms
## arithmetic progression
def printAP(N, A):
 
    ## Declaring a dict
    ## to store positions of all elements
    pos = {}
 
    ## Storing positions of
    ## array elements in dict
    for i in range(N):
        if(A[i] not in pos):
            pos[A[i]] = []
        pos[A[i]].append(i)
 
    ## Declaring a dict to store answer
    ## i.e. key - value pair of element
    ## with their positions forming A.P.
    ## and their common difference
    ans = {}
     
    ## Iterating through the doct "pos"
    for x in pos:
 
        ## If current element is present
        ## only at 1 position, then simply
        ## insert the element in answer
        ## with common difference = 0
        if (len(pos[x]) == 1):
            ans[x] = 0
 
        ## If current element is present
        ## at more than one positions,
        ## then check if all the
        ## positions are at same difference
        else:
            flag = 1
 
            ## Storing the difference of
            ## first two positions in
            ## variable "diff"
            diff = pos[x][1]-pos[x][0]
 
            ## Declaring "prev" to store
            ## previous position of
            ## current element
            prev = pos[x][1];
 
            ## "curr" stores the
            ## Current position of the element
            curr = 0
            length = len(pos[x])
 
            ## Iterating through all the
            ## positions of the current element
            ## and checking id they are in A.P.
            for it in range(2, length):
                curr = pos[x][it];
                if (curr - prev != diff):
                    flag = 0;
                    break;
                prev = curr
 
            ## If all positions of current
            ## element are in A.P.
            ## Insert it into answer with
            ## common difference as "diff"
            if (flag == 1):
                ans[x] = diff
 
    for x in ans:
        print(x, ans[x])
 
## Driver code
if __name__=='__main__':
    N = 8
    A = [1, 2, 1, 3, 1, 2, 1, 5]
    printAP(N, A)
     
    # This code is contributed by subhamgoyal2014.

Javascript




<script>
    // JavaScript code for above approach
 
    // Function to print all elements
    // in given array whose positions forms
    // arithmetic progression
    const printAP = (N, A) => {
 
        // Declaring a hash table(or map)
        // to store positions of all elements
        let pos = {};
 
        // Storing positions of
        // array elements in map
        for (let i = 0; i < N; i++) {
            if (A[i] in pos) pos[A[i]].push(i);
            else pos[A[i]] = [i];
        }
 
        // Declaring a map to store answer
        // i.e. key - value pair of element
        // with their positions forming A.P.
        // and their common difference
        let ans = {};
 
        // Iterating through the map "pos"
        for (let x in pos) {
 
            // If current element is present
            // only at 1 position, then simply
            // insert the element in answer
            // with common difference = 0
            if (pos[x].length == 1) {
                ans[x] = 0;
            }
 
            // If current element is present
            // at more than one positions,
            // then check if all the
            // positions are at same difference
            else {
                let flag = 1;
 
                // Storing the difference of
                // first two positions in
                // variable "diff"
                let diff = pos[x][1] - pos[x][0];
 
                // Declaring "prev" to store
                // previous position of
                // current element
                let prev = pos[x][1];
 
                //"curr" stores the
                // Current position of the element
                let curr;
 
                // Iterating through all the
                // positions of the current element
                // and checking id they are in A.P.
                for (let it = 2; it < pos[x].length; it++) {
                    curr = pos[x][it];
                    if (curr - prev != diff) {
                        flag = 0;
                        break;
                    }
                    prev = pos[x][it];
                }
 
                // If all positions of current
                // element are in A.P.
                // Insert it into answer with
                // common difference as "diff"
                if (flag == 1) {
                    ans[x] = diff;
                }
            }
        }
 
        // Printing the answer
        for (let it in ans) {
            document.write(`${it} ${ans[it]}<br/>`);
        }
    }
 
    // Driver Code
    let N = 8;
    let A = [1, 2, 1, 3, 1, 2, 1, 5];
    printAP(N, A);
 
// This code is contributed by rakeshsahni
 
</script>

 
 

Output

1 2
2 4
3 0
5 0

 

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!