Open In App

Find elements in Array whose positions forms Arithmetic Progression

Last Updated : 27 Oct, 2022
Comments
Improve
Suggest changes
10 Likes
Like
Report

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++
Java Python3 C# JavaScript

 
 


Output
1 2
2 4
3 0
5 0


 

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


 


Next Article

Similar Reads