#2885
Rename Columns
EasyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages built-in functions in pandas to rename columns directly, which is efficient and concise. This approach minimizes the need for manual iteration and copying.
⚙️
Algorithm
2 steps- 1Step 1: Create a mapping dictionary for the old column names to the new column names.
- 2Step 2: Use the pandas rename function with the mapping dictionary to rename the columns in the DataFrame.
solution.py4 lines
1import pandas as pd
2
3def rename_columns_optimal(df):
4 return df.rename(columns={'id': 'student_id', 'first': 'first_name', 'last': 'last_name', 'age': 'age_in_years'})ℹ
Complexity note: The time complexity is O(n) because we are iterating through the DataFrame once. The space complexity is O(n) for the new DataFrame.
- 1Using built-in functions can greatly simplify code and improve performance.
- 2Understanding the structure of data (like DataFrames) is crucial for efficient manipulation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.