Solution: Find Symmetric Pairs in a List

Let’s solve the Find Symmetric Pairs in a List problem.

We'll cover the following

Statement

Given a list of pairs, nums, find all the symmetric pairsBy definition, (a, b) and (c, d) are symmetric pairs iff, a = d and b = c. from it. If no symmetric pair is found, return an empty list.

Constraints:

  • 22 \leq nums.length 103\leq10^3

  • nums[i].length ==2== 2

  • 105-10^5\leq nums[i][1] 105\leq 10^5

  • 105-10^5\leq nums[i][2] 105\leq10^5

Solution

In this solution, we use a set to store the encountered pairs and check whether the symmetric pairs exist.

Here are the steps of the algorithm:

  1. Initialize an empty set, lookup, to store encountered pairs, and an empty list, result, to store symmetric pairs.

  2. Iterate through nums, and for each pair, check if the reverse of it exists in lookup.

    1. If the reverse exists, append the current pair and its reverse to the result list.

    2. Otherwise, add the current pair to lookup.

  3. After iterating through nums, return the result containing symmetric pairs.

Let’s look at the illustration below to better understand the solution:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.