#2881
Create a New Column
EasyArrayDataFrame Manipulation
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)
This approach leverages vectorized operations provided by libraries like pandas in Python, which allows us to perform operations on entire columns at once, making it much faster and more efficient.
⚙️
Algorithm
2 steps- 1Step 1: Use the DataFrame's built-in operations to directly create the bonus column by multiplying the salary column by 2.
- 2Step 2: This operation is done in a single line, which is optimized for performance.
solution.py5 lines
1import pandas as pd
2
3df = pd.DataFrame({'name': ['Piper', 'Grace', 'Georgia', 'Willow', 'Finn', 'Thomas'], 'salary': [4548, 28150, 1103, 6593, 74576, 24433]})
4df['bonus'] = df['salary'] * 2
5print(df)ℹ
Complexity note: The time complexity remains O(n) since we are still iterating through the salaries, but the operations are optimized. The space complexity is O(n) due to the new column for bonuses.
- 1Vectorized operations can significantly improve performance.
- 2Understanding DataFrame operations 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.