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
Constraints:
nums.length
nums[i].length
nums[i][1]
nums[i][2]
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:
Initialize an empty set,
lookup
, to store encountered pairs, and an empty list,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
list.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.