Find elements in Array whose positions forms Arithmetic Progression
Last Updated :
23 Jul, 2025
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>
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem