Symmetric pairs in an array
Last Updated :
04 Apr, 2025
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);
[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);
[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);
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
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
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
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
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
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
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read