Wednesday, November 20, 2024
Google search engine
HomeData Modelling & AIFind elements in Array whose positions forms Arithmetic Progression

Find elements in Array whose positions forms Arithmetic Progression

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


Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to print all elements
  // in given array whose positions forms
  // arithmetic progression
  public static void printAP(int N, int[] A)
  {
 
    // Declaring a hash table(or map)
    // to store positions of all elements
    HashMap<Integer, List<Integer> > pos
      = new HashMap<Integer, List<Integer> >();
     
    // unordered_map<int, vector<int> > pos;
 
    for (int i = 0; i < N; i++) {
      pos.put(A[i], new ArrayList<Integer>());
    }
     
    // Storing positions of
    // array elements in map
    for (int i = 0; i < N; i++)
    {
       
      // pos(pos.get(A[i])).(i);
      pos.get(A[i]).add(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<Integer, Integer> ans
      = new HashMap<Integer, Integer>();
    // map<int, int> ans;
 
    // Iterating through the map "pos"
    for (Integer x : pos.keySet()) {
 
      Integer key = x;
      List<Integer> value = pos.get(x);
 
      // If current element is present
      // only at 1 position, then simply
      // insert the element in answer
      // with common difference = 0
      if (value.size() == 1) {
        ans.put(key, 0);
      }
 
      // If current element is present
      // at more than one positions,
      // then check if all the
      // positions are at same difference
      else {
        int flag = 1;
 
        // Storing the difference of
        // first two positions in
        // variable "diff"
        int diff = value.get(1) - value.get(0);
 
        // Declaring "prev" to store
        // previous position of
        // current element
        int prev = value.get(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 (int it = 2; it < value.size(); it++) {
          curr = value.get(it);
          if (curr - prev != diff) {
            flag = 0;
            break;
          }
          prev = value.get(it);
        }
 
        // If all positions of current
        // element are in A.P.
        // Insert it into answer with
        // common difference as "diff"
        if (flag == 1) {
          ans.put(key, diff);
        }
      }
    }
 
    // Printing the answer
    for (Integer it : ans.keySet()) {
      int key = it;
      int value = ans.get(it);
      System.out.println(key + " " + value);
    }
  }
 
  public static void main(String[] args)
  {
    int N = 8;
    int[] A = { 1, 2, 1, 3, 1, 2, 1, 5 };
    printAP(N, A);
  }
}
 
// This code is contributed by akashish__


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.


C#




/*package whatever //do not write package name here */
using System;
using System.Collections.Generic;
 
class GFG {
 
  // Function to print all elements
  // in given array whose positions forms
  // arithmetic progression
  public static void printAP(int N, int[] A)
  {
 
    // Declaring a hash table(or map)
    // to store positions of all elements
    Dictionary<int, List<int> > pos
      = new Dictionary<int, List<int> >();
     
    // unordered_map<int, vector<int> > pos;
 
    for (int i = 0; i < N; i++) {
      pos[A[i]] = new List<int>();
    }
     
    // Storing positions of
    // array elements in map
    for (int i = 0; i < N; i++)
    {
       
      // pos(pos.get(A[i])).(i);
      pos[A[i]].Add(i);
    }
 
    // Declaring a map to store answer
    // i.e. key - value pair of element
    // with their positions forming A.P.
    // and their common difference
    Dictionary<int, int> ans
      = new Dictionary<int, int>();
    // map<int, int> ans;
 
    // Iterating through the map "pos"
    foreach (int x in pos.Keys) {
 
      int key = x;
      List<int> value = pos[x];
 
      // If current element is present
      // only at 1 position, then simply
      // insert the element in answer
      // with common difference = 0
      if (value.Count == 1) {
        ans[key] = 0;
      }
 
      // If current element is present
      // at more than one positions,
      // then check if all the
      // positions are at same difference
      else {
        int flag = 1;
 
        // Storing the difference of
        // first two positions in
        // variable "diff"
        int diff = value[1] - value[0];
 
        // Declaring "prev" to store
        // previous position of
        // current element
        int prev = value[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 (int it = 2; it < value.Count; it++) {
          curr = value[it];
          if (curr - prev != diff) {
            flag = 0;
            break;
          }
          prev = value[it];
        }
 
        // If all positions of current
        // element are in A.P.
        // Insert it into answer with
        // common difference as "diff"
        if (flag == 1) {
          ans[key] = diff;
        }
      }
    }
 
    // Printing the answer
    foreach (int it in ans.Keys) {
      int key = it;
      int value = ans[it];
      Console.WriteLine(key + " " + value);
    }
  }
 
  public static void Main()
  {
    int N = 8;
    int[] A = { 1, 2, 1, 3, 1, 2, 1, 5 };
    printAP(N, A);
  }
}
 
// This code is contributed by Saurabh Jaiswal


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)

 

Last Updated :
27 Oct, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Take a part in the ongoing discussion

RELATED ARTICLES

Most Popular

Recent Comments