Open In App

Symmetric pairs in an array

Last Updated : 04 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of pairs arr[], a pair (a, b) is said to be symmetric with (c, d) if b = c and a = d. In other words, reversing the elements of one pair should result in the other pair. The first element of each pair is guaranteed to be distinct.

Examples: 

Input: arr[] = [[10, 20], [30, 40], [20, 10], [50, 60]]
Output: [10, 20]
Explanation: [10, 20] and [20, 10] form a symmetric pair.

Input: arr[] = [[1, 2], [2, 3], [3, 4], [4, 1], [3, 2]]
Output: [2, 3]
Explanation: [2, 3] and [3, 2] are symmetric pairs.

Input: arr[] = [[5, 8], [7, 9], [8, 5], [9, 7], [6, 10]]
Output: [5, 8], [7, 9]
Explanation: [5, 8] & [8, 5] and [7, 9] & [9, 7] are symmetric pairs.

[Naive Approach] Using Two Nested Loops - O(n^2) Time and O(1) Space

The idea is to compare each pair with every other pair to check for symmetry. The thought process is to use two nested loops to traverse all possible pairs and verify if arr[i][0] == arr[j][1] and arr[i][1] == arr[j][0]. If a match is found, we store the pair in the result.

C++
// C++ program to find symmetric pairs 
// using a naive approach
#include <bits/stdc++.h>
using namespace std;

// Function to find symmetric pairs
vector<vector<int>> findSymmetricPairs(vector<vector<int>>& arr) {
    
    int n = arr.size();
    vector<vector<int>> result;

    // Traverse all pairs using two nested loops
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {

            // If arr[i] and arr[j] form a symmetric pair
            if (arr[i][0] == arr[j][1] && 
                arr[i][1] == arr[j][0]) {
                result.push_back(arr[i]);
            }
        }
    }

    return result;
}

// Function to print a 2D array
void print2dArray(vector<vector<int>>& arr) {
    for (auto& pair : arr) {
        cout << "[" << pair[0] << ", " << pair[1] << "] ";
    }
    cout << endl;
}

// Driver Code
int main() {

    vector<vector<int>> arr 
           = {{5, 8}, {7, 9}, {8, 5}, {9, 7}, {6, 10}};

    vector<vector<int>> result = findSymmetricPairs(arr);

    print2dArray(result);

    return 0;
}
Java
// Java program to find symmetric pairs 
// using a naive approach
import java.util.*;

class GfG {

    // Function to find symmetric pairs
    static int[][] findSymmetricPairs(int[][] arr) {

        int n = arr.length;
        List<int[]> result = new ArrayList<>();

        // Traverse all pairs using two nested loops
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // If arr[i] and arr[j] form a symmetric pair
                if (arr[i][0] == arr[j][1] && 
                    arr[i][1] == arr[j][0]) {
                    result.add(arr[i]);
                }
            }
        }

        return result.toArray(new int[result.size()][]);
    }

    // Function to print a 2D array
    static void print2dArray(int[][] arr) {
        for (int[] pair : arr) {
            System.out.print("[" + pair[0] + ", " + pair[1] + "] ");
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {

        int[][] arr = {{5, 8}, {7, 9}, {8, 5}, {9, 7}, {6, 10}};

        int[][] result = findSymmetricPairs(arr);

        print2dArray(result);
    }
}
Python
# Python program to find symmetric pairs 
# using a naive approach

# Function to find symmetric pairs
def findSymmetricPairs(arr):

    n = len(arr)
    result = []

    # Traverse all pairs using two nested loops
    for i in range(n):
        for j in range(i + 1, n):

            # If arr[i] and arr[j] form a symmetric pair
            if arr[i][0] == arr[j][1] and arr[i][1] == arr[j][0]:
                result.append(arr[i])

    return result

# Function to print a 2D array
def print2dArray(arr):
    for pair in arr:
        print(f"[{pair[0]}, {pair[1]}]", end=" ")
    print()

# Driver Code
if __name__ == "__main__":

    arr = [[5, 8], [7, 9], [8, 5], [9, 7], [6, 10]]

    result = findSymmetricPairs(arr)

    print2dArray(result)
C#
// C# program to find symmetric pairs 
// using a naive approach
using System;
using System.Collections.Generic;

class GfG {

    // Function to find symmetric pairs
    public static int[][] findSymmetricPairs(int[][] arr) {

        int n = arr.Length;
        List<int[]> result = new List<int[]>();

        // Traverse all pairs using two nested loops
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // If arr[i] and arr[j] form a symmetric pair
                if (arr[i][0] == arr[j][1] && 
                    arr[i][1] == arr[j][0]) {
                    result.Add(arr[i]);
                }
            }
        }

        return result.ToArray();
    }

    // Function to print a 2D array
    public static void print2dArray(int[][] arr) {
        foreach (var pair in arr) {
            Console.Write("[" + pair[0] + ", " + pair[1] + "] ");
        }
        Console.WriteLine();
    }

    // Driver Code
    public static void Main() {

        int[][] arr = {new int[] {5, 8}, new int[] {7, 9}, 
                       new int[] {8, 5}, new int[] {9, 7}, 
                       new int[] {6, 10}};

        int[][] result = findSymmetricPairs(arr);

        print2dArray(result);
    }
}
JavaScript
// JavaScript program to find symmetric pairs 
// using a naive approach

// Function to find symmetric pairs
function findSymmetricPairs(arr) {

    let n = arr.length;
    let result = [];

    // Traverse all pairs using two nested loops
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {

            // If arr[i] and arr[j] form a symmetric pair
            if (arr[i][0] === arr[j][1] && 
                arr[i][1] === arr[j][0]) {
                result.push(arr[i]);
            }
        }
    }

    return result;
}

// Function to print a 2D array
function print2dArray(arr) {
    for (let pair of arr) {
        process.stdout.write(`[${pair[0]}, ${pair[1]}] `);
    }
    console.log();
}

// Driver Code
let arr = [[5, 8], [7, 9], [8, 5], [9, 7], [6, 10]];

let result = findSymmetricPairs(arr);

print2dArray(result);

Output
[5, 8] [7, 9] 

[Better Approach] Using Binary Search - O(nlog(n)) Time and O(1) Space

The idea is to first sort the given arr[] based on the first element of each pair. This allows efficient searching using binary search, reducing the time complexity compared to the previous approach. For each pair, we search for its potential symmetric pair in the sorted array and verify if it exists. The sorting step ensures that we only look ahead, preventing duplicate checks and improving efficiency.

C++
// C++ program to find symmetric pairs 
// using sorting and binary search
#include <bits/stdc++.h>
using namespace std;

// Binary search helper function
bool binarySearch(vector<vector<int>>& arr, int low, 
                  int high, int key) {

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid][0] == key) {
            return true;
        } else if (arr[mid][0] < key) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return false;
}

// Function to find symmetric pairs
vector<vector<int>> findSymmetricPairs(vector<vector<int>>& arr) {
    
    int n = arr.size();
    vector<vector<int>> result;

    // Sort pairs based on the first element
    sort(arr.begin(), arr.end());

    // Traverse all pairs and use binary search
    for (int i = 0; i < n; i++) {
        int key = arr[i][1];

        // Check if key exists as a first element
        if (binarySearch(arr, i + 1, n - 1, key)) {
            
            // Verify if it's a symmetric pair
            for (int j = i + 1; j < n; j++) {
                if (arr[j][0] == key && arr[j][1] == arr[i][0]) {
                    result.push_back(arr[i]);
                    break;
                }
            }
        }
    }

    return result;
}

void print2dArray(vector<vector<int>>& arr) {
    for (auto& pair : arr) {
        cout << "[" << pair[0] << ", " << pair[1] << "] ";
    }
    cout << endl;
}

// Driver Code
int main() {

    vector<vector<int>> arr 
           = {{5, 8}, {7, 9}, {8, 5}, {9, 7}, {6, 10}};

    vector<vector<int>> result = findSymmetricPairs(arr);

    print2dArray(result);

    return 0;
}
Java
// Java program to find symmetric pairs 
// using sorting and binary search
import java.util.Arrays;

class GfG {

    // Binary search helper function
    static boolean binarySearch(int[][] arr, int low, 
                                int high, int key) {
        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (arr[mid][0] == key) {
                return true;
            } else if (arr[mid][0] < key) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return false;
    }

    // Function to find symmetric pairs
    static int[][] findSymmetricPairs(int[][] arr) {
        int n = arr.length;
        int[][] result = new int[n][2];
        int count = 0;

        // Sort pairs based on the first element
        Arrays.sort(arr, (a, b) -> a[0] - b[0]);

        // Traverse all pairs and use binary search
        for (int i = 0; i < n; i++) {
            int key = arr[i][1];

            // Check if key exists as a first element
            if (binarySearch(arr, i + 1, n - 1, key)) {

                // Verify if it's a symmetric pair
                for (int j = i + 1; j < n; j++) {
                    if (arr[j][0] == key && arr[j][1] == arr[i][0]) {
                        result[count++] = arr[i];
                        break;
                    }
                }
            }
        }

        return Arrays.copyOf(result, count);
    }

    // Function to print a 2D array
    static void print2dArray(int[][] arr) {
        for (int[] pair : arr) {
            System.out.print("[" + pair[0] + ", " + pair[1] + "] ");
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {
        int[][] arr = { {5, 8}, {7, 9}, {8, 5}, {9, 7}, {6, 10} };

        int[][] result = findSymmetricPairs(arr);

        print2dArray(result);
    }
}
Python
# Python program to find symmetric pairs 
# using sorting and binary search

# Binary search helper function
def binarySearch(arr, low, high, key):
    while low <= high:
        mid = low + (high - low) // 2

        if arr[mid][0] == key:
            return True
        elif arr[mid][0] < key:
            low = mid + 1
        else:
            high = mid - 1

    return False

# Function to find symmetric pairs
def findSymmetricPairs(arr):
    n = len(arr)
    result = []

    # Sort pairs based on the first element
    arr.sort()

    # Traverse all pairs and use binary search
    for i in range(n):
        key = arr[i][1]

        # Check if key exists as a first element
        if binarySearch(arr, i + 1, n - 1, key):

            # Verify if it's a symmetric pair
            for j in range(i + 1, n):
                if arr[j][0] == key and arr[j][1] == arr[i][0]:
                    result.append(arr[i])
                    break

    return result

# Function to print a 2D array
def print2dArray(arr):
    for pair in arr:
        print(f"[{pair[0]}, {pair[1]}]", end=" ")
    print()

# Driver Code
if __name__ == "__main__":
    arr = [[5, 8], [7, 9], [8, 5], [9, 7], [6, 10]]

    result = findSymmetricPairs(arr)

    print2dArray(result)
C#
// C# program to find symmetric pairs 
// using sorting and binary search
using System;
using System.Collections.Generic;

class GfG {

    // Binary search helper function
    static bool BinarySearch(List<int[]> arr, int low, 
                             int high, int key) {
        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (arr[mid][0] == key) {
                return true;
            } else if (arr[mid][0] < key) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return false;
    }

    // Function to find symmetric pairs
    static List<int[]> FindSymmetricPairs(int[,] arr) {
        int n = arr.GetLength(0);
        List<int[]> sortedArr = new List<int[]>();

        // Convert 2D array to list
        for (int i = 0; i < n; i++) {
            sortedArr.Add(new int[] { arr[i, 0], arr[i, 1] });
        }

        // Sort pairs based on the first element
        sortedArr.Sort((a, b) => a[0].CompareTo(b[0]));

        List<int[]> result = new List<int[]>();

        // Traverse all pairs and use binary search
        for (int i = 0; i < n; i++) {
            int key = sortedArr[i][1];

            // Check if key exists as a first element
            if (BinarySearch(sortedArr, i + 1, n - 1, key)) {

                // Verify if it's a symmetric pair
                for (int j = i + 1; j < n; j++) {
                    if (sortedArr[j][0] == key && 
                        sortedArr[j][1] == sortedArr[i][0]) {
                        result.Add(new int[] { sortedArr[i][0], sortedArr[i][1] });
                        break;
                    }
                }
            }
        }

        return result;
    }

    // Function to print a 2D array
    static void Print2dArray(List<int[]> arr) {
        foreach (var pair in arr) {
            Console.Write("[" + pair[0] + ", " + pair[1] + "] ");
        }
        Console.WriteLine();
    }

    // Driver Code
    static void Main() {
        int[,] arr = { {5, 8}, {7, 9}, {8, 5}, {9, 7}, {6, 10} };

        List<int[]> result = FindSymmetricPairs(arr);

        Print2dArray(result);
    }
}
JavaScript
// JavaScript program to find symmetric pairs 
// using sorting and binary search

// Binary search helper function
function binarySearch(arr, low, high, key) {
    while (low <= high) {
        let mid = Math.floor(low + (high - low) / 2);

        if (arr[mid][0] === key) {
            return true;
        } else if (arr[mid][0] < key) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return false;
}

// Function to find symmetric pairs
function findSymmetricPairs(arr) {
    let n = arr.length;
    let result = [];

    // Sort pairs based on the first element
    arr.sort((a, b) => a[0] - b[0]);

    // Traverse all pairs and use binary search
    for (let i = 0; i < n; i++) {
        let key = arr[i][1];

        // Check if key exists as a first element
        if (binarySearch(arr, i + 1, n - 1, key)) {

            // Verify if it's a symmetric pair
            for (let j = i + 1; j < n; j++) {
                if (arr[j][0] === key && arr[j][1] === arr[i][0]) {
                    result.push(arr[i]);
                    break;
                }
            }
        }
    }

    return result;
}

// Function to print a 2D array
function print2dArray(arr) {
    arr.forEach(pair => {
        console.log(`[${pair[0]}, ${pair[1]}]`, " ");
    });
}

// Driver Code
let arr = [[5, 8], [7, 9], [8, 5], [9, 7], [6, 10]];

let result = findSymmetricPairs(arr);

print2dArray(result);

Output
[5, 8] [7, 9] 

[Expected Approach] Using Hashing - O(n) Time and O(n) Space

The idea is to use hashing for an efficient linear solution. We store each [first, second] pair in a hash table. When processing a new pair, we check if its reverse exists in the map. If found, the pair is symmetric, so we add it to the result.

C++
// C++ program to find symmetric pairs 
// using hashing
#include <bits/stdc++.h>
using namespace std;

// Function to find symmetric pairs
vector<vector<int>> findSymmetricPairs(vector<vector<int>>& arr) {
    
    int n = arr.size();
    vector<vector<int>> result;
    
    // HashMap to store pairs
    unordered_map<int, int> hash;

    // Traverse all pairs
    for (int i = 0; i < n; i++) {
        int first = arr[i][0];
        int second = arr[i][1];

        // If reverse pair exists in hash, it's symmetric
        if (hash.find(second) != hash.end() && 
            hash[second] == first) {
            result.push_back({second, first});
        } else {
            // Store the current pair in hash
            hash[first] = second;
        }
    }

    return result;
}

// Function to print a 2D array
void print2dArray(vector<vector<int>>& arr) {
    for (auto& pair : arr) {
        cout << "[" << pair[0] << ", " << pair[1] << "] ";
    }
    cout << endl;
}

// Driver Code
int main() {

    vector<vector<int>> arr 
           = {{5, 8}, {7, 9}, {8, 5}, {9, 7}, {6, 10}};

    vector<vector<int>> result = findSymmetricPairs(arr);

    print2dArray(result);

    return 0;
}
Java
// Java program to find symmetric pairs 
// using hashing
import java.util.*;

class GfG {

    // Function to find symmetric pairs
    static int[][] findSymmetricPairs(int[][] arr) {
        
        int n = arr.length;
        List<int[]> result = new ArrayList<>();
        
        // HashMap to store pairs
        HashMap<Integer, Integer> hash = new HashMap<>();

        // Traverse all pairs
        for (int i = 0; i < n; i++) {
            int first = arr[i][0];
            int second = arr[i][1];

            // If reverse pair exists in hash, it's symmetric
            if (hash.containsKey(second) && 
                hash.get(second) == first) {
                result.add(new int[]{second, first});
            } else {
                // Store the current pair in hash
                hash.put(first, second);
            }
        }

        return result.toArray(new int[result.size()][]);
    }

    // Function to print a 2D array
    static void print2dArray(int[][] arr) {
        for (int[] pair : arr) {
            System.out.print("[" + pair[0] + ", " + pair[1] + "] ");
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {

        int[][] arr = {{5, 8}, {7, 9}, {8, 5}, {9, 7}, {6, 10}};

        int[][] result = findSymmetricPairs(arr);

        print2dArray(result);
    }
}
Python
# Python program to find symmetric pairs 
# using hashing

# Function to find symmetric pairs
def findSymmetricPairs(arr):
    
    n = len(arr)
    result = []
    
    # Dictionary to store pairs
    hash = {}

    # Traverse all pairs
    for first, second in arr:

        # If reverse pair exists in hash, it's symmetric
        if second in hash and hash[second] == first:
            result.append([second, first])
        else:
            # Store the current pair in hash
            hash[first] = second

    return result

# Function to print a 2D array
def print2dArray(arr):
    for pair in arr:
        print(f"[{pair[0]}, {pair[1]}]", end=" ")
    print()

# Driver Code
if __name__ == "__main__":

    arr = [[5, 8], [7, 9], [8, 5], [9, 7], [6, 10]]

    result = findSymmetricPairs(arr)

    print2dArray(result)
C#
// C# program to find symmetric pairs 
// using hashing
using System;
using System.Collections.Generic;

class GfG {

    // Function to find symmetric pairs
    static int[][] findSymmetricPairs(int[][] arr) {
        
        int n = arr.Length;
        List<int[]> result = new List<int[]>();
        
        // Dictionary to store pairs
        Dictionary<int, int> hash = new Dictionary<int, int>();

        // Traverse all pairs
        for (int i = 0; i < n; i++) {
            int first = arr[i][0];
            int second = arr[i][1];

            // If reverse pair exists in hash, it's symmetric
            if (hash.ContainsKey(second) && 
                hash[second] == first) {
                result.Add(new int[]{second, first});
            } else {
                // Store the current pair in hash
                hash[first] = second;
            }
        }

        return result.ToArray();
    }

    // Function to print a 2D array
    static void print2dArray(int[][] arr) {
        foreach (int[] pair in arr) {
            Console.Write("[" + pair[0] + ", " + pair[1] + "] ");
        }
        Console.WriteLine();
    }

    // Driver Code
    static void Main() {

        int[][] arr = { new int[]{5, 8}, new int[]{7, 9}, 
                        new int[]{8, 5}, new int[]{9, 7}, 
                        new int[]{6, 10} };

        int[][] result = findSymmetricPairs(arr);

        print2dArray(result);
    }
}
JavaScript
// JavaScript program to find symmetric pairs 
// using hashing

// Function to find symmetric pairs
function findSymmetricPairs(arr) {
    
    let n = arr.length;
    let result = [];
    
    // Map to store pairs
    let hash = new Map();

    // Traverse all pairs
    for (let [first, second] of arr) {

        // If reverse pair exists in hash, it's symmetric
        if (hash.has(second) && hash.get(second) === first) {
            result.push([second, first]);
        } else {
            // Store the current pair in hash
            hash.set(first, second);
        }
    }

    return result;
}

// Function to print a 2D array
function print2dArray(arr) {
    for (let pair of arr) {
        console.log(`[${pair[0]}, ${pair[1]}] `);
    }
}

// Driver Code
let arr = [[5, 8], [7, 9], [8, 5], [9, 7], [6, 10]];

let result = findSymmetricPairs(arr);

print2dArray(result);

Output
[5, 8] [7, 9] 

Next Article
Article Tags :
Practice Tags :

Similar Reads