#1795

Rearrange Products Table

Easy
DatabaseHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal approach leverages SQL's ability to handle data transformation efficiently using the UNION ALL operator, which allows us to combine results from multiple SELECT statements into one result set.

⚙️

Algorithm

2 steps
  1. 1Step 1: Use a SELECT statement to get product_id, store1, and its price, filtering out nulls.
  2. 2Step 2: Repeat for store2 and store3, using UNION ALL to combine results.
solution.py2 lines
1def rearrange_products(products):
2    return products.melt(id_vars=['product_id'], value_vars=['store1', 'store2', 'store3'], var_name='store', value_name='price').dropna()

Complexity note: The time complexity is O(n) because we are processing each product once. The space complexity is O(n) due to the storage of results in a new list.

  • 1Using UNION ALL in SQL can simplify data transformation tasks.
  • 2Data can be reshaped efficiently using built-in functions in programming languages.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.