EasyNo. 0627

Swap Sex of Employees — LeetCode 627 Python Solution

Topics
Database
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

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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0626Exchange SeatsMedium
0620Not Boring MoviesEasy
0619Biggest Single NumberEasy
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium

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.

Free to download. Check it runs on your machine, then pick a plan.