LeetCode 2890: Reshape Data: Melt

Problem Description

Explanation:

To reshape the data from wide to long format, we need to iterate over the columns representing the quarters and create a new row for each product and quarter combination.

  1. Iterate over each product.
  2. For each product, iterate over the quarters and create a new row with the product name, quarter name, and sales value.
  3. Repeat this process for all products and quarters to reshape the data.

Time Complexity: O(n*m) where n is the number of products and m is the number of quarters.

Space Complexity: O(n*m) for the reshaped data.

:

Solutions

public List<List<String>> reshapeData(List<List<String>> data) {
    List<List<String>> reshapedData = new ArrayList<>();
    
    reshapedData.add(Arrays.asList("product", "quarter", "sales"));
    
    for (int i = 1; i < data.get(0).size(); i++) {
        String quarter = "quarter_" + i;
        for (int j = 1; j < data.size(); j++) {
            List<String> row = new ArrayList<>();
            row.add(data.get(j).get(0)); // product
            row.add(quarter);
            row.add(data.get(j).get(i)); // sales
            reshapedData.add(row);
        }
    }
    
    return reshapedData;
}

Loading editor...