Swap Sex of Employees — LeetCode 627 Python Solution

EasyDatabase
Problem
#627
Reading time
2 min

The problem

Flip the sex column of every row in place, turning every m into an f and every f into an m, with a single update statement and no temporary table. The answer is the Salary table itself once the update has run. The Salary table has one row per employee: id (int, the primary key), name (varchar), sex (an enum whose only values are 'm' and 'f') and salary (int).

Example

Salary table:

| id | name  | sex | salary |
| -- | ----- | --- | ------ |
| 1  | Lena  | f   | 5200   |
| 2  | Marco | m   | 4800   |
| 3  | Nia   | f   | 6100   |
| 4  | Omar  | m   | 4400   |

Salary table after the update:

| id | name  | sex | salary |
| -- | ----- | --- | ------ |
| 1  | Lena  | m   | 5200   |
| 2  | Marco | f   | 4800   |
| 3  | Nia   | m   | 6100   |
| 4  | Omar  | f   | 4400   |

Every value in the sex column is replaced by its opposite in one pass, and no other column moves.

Python solution

Python
import pandas as pd

def swap_sex(salary: pd.DataFrame) -> pd.DataFrame:
    df = salary.copy()
    df['sex'] = df['sex'].map(lambda x: 'f' if x == 'm' else 'm')
    return df

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 627. Swap Sex of Employees?
LeetCode 627. Swap Sex of Employees is rated Easy on LeetCode.
What topics does LeetCode 627. Swap Sex of Employees cover?
LeetCode 627. Swap Sex of Employees is tagged Database on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview