Skip to main content
Back to problems
#2978
Medium Database

Symmetric coordinates

Database
40.8% acceptance
Mar 31, 2026
14
3

No description available.

Solution

Pandas
Time O(1)
Space O(1)
LeetCode
solution.pandas
# Table: Coordinates
# 
# +-------------+------+
# | Column Name | Type |
# +-------------+------+
# | X           | int  |
# | Y           | int  |
# +-------------+------+
# Each row includes X and Y, where both are integers. Table may contain duplicate values.
# 
# Two coordindates (X1, Y1) and (X2, Y2) are said to be symmetric coordintes if X1 == Y2 and X2 == Y1.
# 
# Write a solution that outputs, among all these symmetric coordintes, only those unique coordinates that satisfy the condition X1 <= Y1.
# 
# Return the result table ordered by X and  Y (respectively) in ascending order.
# 
# The result format is in the following example.
#
# Example 1:
# Input:
# Coordinates table:
# +----+----+
# | X  | Y  |
# +----+----+
# | 20 | 20 |
# | 20 | 20 |
# | 20 | 21 |
# | 23 | 22 |
# | 22 | 23 |
# | 21 | 20 |
# +----+----+
# Output:
# +----+----+
# | x  | y  |
# +----+----+
# | 20 | 20 |
# | 20 | 21 |
# | 22 | 23 |
# +----+----+
# Explanation:
# - (20, 20) and (20, 20) are symmetric coordinates because, X1 == Y2 and X2 == Y1. This results in displaying (20, 20) as a distinctive coordinates.
# - (20, 21) and (21, 20) are symmetric coordinates because, X1 == Y2 and X2 == Y1. However, only (20, 21) will be displayed because X1 <= Y1.
# - (23, 22) and (22, 23) are symmetric coordinates because, X1 == Y2 and X2 == Y1. However, only (22, 23) will be displayed because X1 <= Y1.
# The output table is sorted by X and Y in ascending order.

import pandas as pd

def symmetric_pairs(coordinates: pd.DataFrame) -> pd.DataFrame:
  coordinates = coordinates.reset_index()
  merged = coordinates.merge(coordinates, left_on=['X', 'Y'], right_on=['Y', 'X'], suffixes=('_1', '_2'))
  merged = merged[merged['index_1'] != merged['index_2']]
  merged = merged[merged['X_1'] <= merged['Y_1']]
  result = merged[['X_1', 'Y_1']].drop_duplicates()
  result.columns = ['x', 'y']
  return result.sort_values(['x', 'y']).reset_index(drop=True)