Students Report By Geography — LeetCode 618 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #618
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Pivot the students into three columns named America, Asia and Europe, each column listing that continent's students in alphabetical order. The rows line up by position, and a continent that runs out of students is padded with null. The Student table has one row per student and may contain duplicate rows: name (varchar) and continent (varchar, one of America, Asia or Europe).
Example
Student table: | name | continent | | ----- | --------- | | Diego | America | | Hana | Asia | | Ines | Europe | | Mateo | America | | Yuki | Asia | Result: | America | Asia | Europe | | ------- | ---- | ------ | | Diego | Hana | Ines | | Mateo | Yuki | null | Each continent is sorted on its own and then written down its column, so the second row pads Europe with null because it has only one student.
Python solution
Python
import pandas as pd
def students_report_by_geography(student: pd.DataFrame) -> pd.DataFrame:
df = student.sort_values('name').copy()
df['rn'] = df.groupby('continent').cumcount()
wide = df.pivot(index='rn', columns='continent', values='name')
for continent in ('America', 'Asia', 'Europe'):
if continent not in wide:
wide[continent] = None
res = wide[['America', 'Asia', 'Europe']].rename_axis(None, axis=1)
return res.reset_index(drop=True)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 618. Students Report By Geography?
- LeetCode 618. Students Report By Geography is rated Hard on LeetCode.
- What topics does LeetCode 618. Students Report By Geography cover?
- LeetCode 618. Students Report By Geography is tagged Database on LeetCode.
- Is LeetCode 618. Students Report By Geography a premium problem?
- Yes. LeetCode 618. Students Report By Geography is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.