Solution: Find Symmetric Pairs in an Array
Let’s solve the Find Symmetric Pairs in an Array problem.
We'll cover the following
Statement
Given an array of pairs, nums
, find all the
Constraints:
nums.length
nums[i].length
nums[i][1]
nums[i][2]
Solution
In this solution, we use an unordered set to store the encountered pairs and check whether the symmetric pairs exist.
Here are the steps of the algorithm:
Initialize an empty unordered set,
lookup
, to store encountered pairs, and an empty array,result
, to store symmetric pairs.Iterate through
nums
, and for each pair, check if the reverse of it exists inlookup
.If the reverse exists, append the current pair and its reverse to the
result
array.Otherwise, add the current pair to
lookup
.
After iterating through
nums
, return theresult
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.