#2879
Display the First Three Rows
EasyArrayDataFrame Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages built-in functions to directly access the first three rows of the DataFrame, making it efficient and concise.
⚙️
Algorithm
2 steps- 1Step 1: Use the built-in method to select the first three rows of the DataFrame.
- 2Step 2: Return the result directly.
solution.py13 lines
1# Full working Python code
2import pandas as pd
3
4df = pd.DataFrame({
5 'employee_id': [3, 90, 9, 60, 49, 43],
6 'name': ['Bob', 'Alice', 'Tatiana', 'Annabelle', 'Jonathan', 'Khaled'],
7 'department': ['Operations', 'Sales', 'Engineering', 'InformationTechnology', 'HumanResources', 'Administration'],
8 'salary': [48675, 11096, 33805, 37678, 23793, 40454]
9})
10
11# Optimal solution
12first_three_rows = df.head(3)
13print(first_three_rows)ℹ
Complexity note: The time complexity is O(n) because we are accessing the first three rows directly, which involves iterating through the DataFrame. The space complexity is O(n) as we store the rows in a new structure.
- 1Using built-in functions can greatly simplify code and improve performance.
- 2Understanding the structure of DataFrames is crucial for efficient data manipulation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.