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 ordervoid 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 Codeint 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 approachimport 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 orderdef 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 Codeif __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 approachusing 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 orderfunction 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 Codeconst arr = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2];const N = arr.length;Â
// Function callrepeated_pairs(arr, N);Â
Â
// This code is contributed by Aditya Sharma |
1 2 2 3 3 4 4 1
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Read More Information here on that Topic: geeksforgeeks.org/print-all-repeating-adjacent-pairs-in-sorted-order-from-an-array/ […]