#2890

Reshape Data: Melt

Easy
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using built-in functions in pandas allows us to reshape the DataFrame efficiently without manually iterating through rows and columns. This method leverages optimized internal operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use the pandas melt function to reshape the DataFrame.
  2. 2Step 2: Specify the id_vars as 'product' and value_vars as the quarters.
  3. 3Step 3: The melt function will automatically create the desired long format.
solution.py5 lines
1# Full working Python code
2import pandas as pd
3
4def reshape_data_optimal(df):
5    return df.melt(id_vars=['product'], value_vars=['quarter_1', 'quarter_2', 'quarter_3', 'quarter_4'], var_name='quarter', value_name='sales')

Complexity note: The time complexity is O(n) because the melt function processes each row once. The space complexity is O(n) as it creates a new DataFrame to store the reshaped data.

  • 1Using built-in functions can significantly reduce complexity.
  • 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.