![]() |
VOOZH | about |
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.
Table of Content
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.
[5, 8] [7, 9]
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.
[5, 8] [7, 9]
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.
[5, 8] [7, 9]