Print all repeating adjacent pairs in sorted order from an array
Last Updated :
01 Mar, 2023
Given an array arr[] consisting of N integers, the task is to print all adjacent integer pairs from the array which appears more than once in the given array. If the array contains more than one such pair, print all pairs in sorted order.
Examples:
Input: arr[] = {1, 2, 5, 1, 2}
Output:
1 2
Explanation:
1 2 is the only repeating integer pair in the array.
Input: arr[] = {1, 2, 3, 4, 1, 2, 3, 4, 1, 2}
Output:
1 2
2 3
3 4
4 1
Explanation:
Since the array has more than one repeating pair, all the pairs are printed in the sorted order.
Approach: The simplest approach is to traverse the array and store every adjacent pair in a Map. Print all such pairs having frequency greater than 1. Follow the steps below to solve the problem:
- Create a Map M to store all adjacent pairs in an array.
- Traverse the given array and store every adjacent pair in the Map M.
- After the above step, traverse the map, and if the frequency of any pair is at least one, then insert it into a vector V.
- Sort the vector v in ascending order and print all the pairs stored in it.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print adjacent pairs
// in sorted order
void repeated_pairs(int arr[], int N)
{
// Store the frequency of all
// the adjacent pairs
map<pair<int, int>, int> m;
// Stores the resultant pairs
vector<pair<int, int> > v;
int i, j;
// Stores the count of all
// adjacent pairs
for (i = 0; i < N - 1; i++) {
pair<int, int> p
= { arr[i], arr[i + 1] };
// Increment the count of pair
m[p]++;
}
// Store pairs that appears more
// than once
for (auto i = m.begin();
i != m.end(); i++) {
// If frequency is at least 1
if (i->second > 1) {
pair<int, int> p = i->first;
// Insert pair into vector
v.push_back(p);
}
}
// Sort the vector
sort(v.begin(), v.end());
// Print the pairs
for (i = 0; i < v.size(); i++) {
pair<int, int> p = v[i];
// Print the pair
cout << p.first << " "
<< p.second << endl;
}
}
// Driver Code
int main()
{
// Given arr[]
int arr[] = { 1, 2, 3, 4, 1,
2, 3, 4, 1, 2 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
repeated_pairs(arr, N);
return 0;
}
Java
// Java code of above approach
import java.util.*;
import java.lang.*;
class pair
{
int first, second;
pair(int f, int s)
{
this.first = f;
this.second = s;
}
@Override
public boolean equals(Object obj)
{
// if both the object references are
// referring to the same object.
if(this == obj)
return true;
if(obj == null || obj.getClass() != this.getClass())
return false;
// type casting of the argument.
pair p = (pair) obj;
return (p.first == this.first && p.second == this.second);
}
@Override
public int hashCode()
{
return this.first + this.second/2;
}
}
class GFG {
// Function to print adjacent pairs
// in sorted order
static void repeated_pairs(int arr[], int N)
{
// Store the frequency of all
// the adjacent pairs
Map<pair, Integer> m=new HashMap<>();
// Stores the resultant pairs
ArrayList<pair> v = new ArrayList<>();
int i, j;
// Stores the count of all
// adjacent pairs
for (i = 0; i < N - 1; i++)
{
pair p = new pair(arr[i], arr[i + 1]);
// Increment the count of pair
m.put(p,m.getOrDefault(p, 0) + 1);
}
// Store pairs that appears more
// than once
for (Map.Entry<pair,Integer> k: m.entrySet())
{
// If frequency is at least
if (k.getValue() > 1)
{
// Insert pair into vector
v.add(k.getKey());
}
}
// Sort the vector
Collections.sort(v, (a, b)->a.first-b.first);
// Print the pairs
for (pair k:v)
{
// Print the pair
System.out.println(k.first + " " + k.second);
}
}
// Driver code
public static void main(String[] args)
{
// Given arr[]
int arr[] = { 1, 2, 3, 4, 1,
2, 3, 4, 1, 2 };
int N = arr.length;
// Function call
repeated_pairs(arr, N);
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
# Function to print adjacent pairs
# in sorted order
def repeated_pairs(arr, N):
# Store the frequency of all
# the adjacent pairs
m = {}
# Stores the resultant pairs
v = []
# Stores the count of all
# adjacent pairs
for i in range(N - 1):
p = (arr[i], arr[i + 1])
# Increment the count of pair
m[p] = m.get(p, 0) + 1
# Store pairs that appears more
# than once
for i in m:
# If frequency is at least 1
if (m[i] > 1):
p = i
# Insert pair into vector
v.append(p)
# Sort the vector
v = sorted(v)
# Print the pairs
for i in range(len(v)):
p = v[i]
# Print the pair
print(p[0], p[1])
# Driver Code
if __name__ == '__main__':
# Given arr[]
arr = [ 1, 2, 3, 4, 1,
2, 3, 4, 1, 2 ]
N = len(arr)
# Function call
repeated_pairs(arr, N)
# This code is contributed by mohit kumar 29
C#
// C# code of above approach
using System;
using System.Collections.Generic;
using System.Linq;
class pair
{
public int first, second;
public pair(int f, int s)
{
this.first = f;
this.second = s;
}
public override bool Equals(Object obj)
{
// if both the object references are
// referring to the same object.
if (this == obj)
return true;
if (obj == null || obj.GetType() != this.GetType())
return false;
// type casting of the argument.
pair p = (pair)obj;
return (p.first == this.first && p.second == this.second);
}
public override int GetHashCode()
{
return this.first + this.second / 2;
}
}
class GFG
{
// Function to print adjacent pairs
// in sorted order
static void repeated_pairs(int[] arr, int N)
{
// Store the frequency of all
// the adjacent pairs
Dictionary<pair, int> m = new Dictionary<pair, int>();
// Stores the resultant pairs
List<pair> v = new List<pair>();
// Stores the count of all
// adjacent pairs
for (int i = 0; i < N - 1; i++)
{
pair p = new pair(arr[i], arr[i + 1]);
if (!m.ContainsKey(p))
{
m[p] = 0;
}
// Increment the count of pair
m[p]++;
}
// Store pairs that appears more
// than once
foreach (KeyValuePair<pair, int> k in m)
{
// If frequency is at least
if (k.Value > 1)
{
// Insert pair into vector
v.Add(k.Key);
}
}
// Sort the vector
v.Sort((a, b) => a.first - b.first);
// print the pair
foreach (pair k in v)
{
// print pair
Console.WriteLine(k.first + " " + k.second);
}
}
// Driver code
public static void Main(string[] args)
{
// Given arr[]
int[] arr = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 };
int N = arr.Length
// Function call
repeated_pairs(arr, N);
}
}
// This code is contributed by Aditya Sharma
JavaScript
// Function to print adjacent pairs
// in sorted order
function repeated_pairs(arr, N) {
// Store the frequency of all
// the adjacent pairs
const m = {};
// Stores the resultant pairs
const v = [];
// Stores the count of all
// adjacent pairs
for (let i = 0; i < N - 1; i++) {
const p = [arr[i], arr[i + 1]];
// Increment the count of pair
m[p] = (m[p] || 0) + 1;
}
// Store pairs that appears more
// than once
for (let i in m) {
// If frequency is at least 1
if (m[i] > 1) {
const p = i.split(',');
// Insert pair into vector
v.push([parseInt(p[0]), parseInt(p[1])]);
}
}
// Sort the vector
v.sort();
// Print the pairs
for (let i = 0; i < v.length; i++) {
const p = v[i];
// Print the pair
console.log(p[0], p[1]);
}
}
// Driver Code
const arr = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2];
const N = arr.length;
// Function call
repeated_pairs(arr, N);
// This code is contributed by Aditya Sharma
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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