LeetCode 2889: Reshape Data: Pivot Solution

Master LeetCode problem 2889 (Reshape Data: Pivot), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2889. Reshape Data: Pivot

Easy

Problem Explanation

Explanation:

To solve this problem, we need to pivot the given data such that each row represents temperatures for a specific month, and each city is a separate column in the output.

  1. Create a map where the keys are the months and the values are maps where the keys are cities and the values are corresponding temperatures.
  2. Iterate through the input data and populate this map.
  3. Create the output table by iterating through the map to fill in the temperatures for each city in the corresponding month.

Time Complexity: O(n) where n is the number of entries in the input data
Space Complexity: O(n) for storing the data in the map

:

Solution Code

import java.util.*;

class Solution {
    public List<List<String>> pivotTable(List<List<String>> data) {
        Map<String, Map<String, String>> tempMap = new HashMap<>();
        List<List<String>> result = new ArrayList<>();

        for (List<String> entry : data) {
            String city = entry.get(0);
            String month = entry.get(1);
            String temperature = entry.get(2);

            if (!tempMap.containsKey(month)) {
                tempMap.put(month, new LinkedHashMap<>());
            }

            tempMap.get(month).put(city, temperature);
        }

        List<String> header = new ArrayList<>();
        header.add("month");
        for (String city : tempMap.get(data.get(0).get(1)).keySet()) {
            header.add(city);
        }
        result.add(header);

        for (String month : tempMap.keySet()) {
            List<String> row = new ArrayList<>();
            row.add(month);
            for (String city : tempMap.get(month).keySet()) {
                row.add(tempMap.get(month).get(city));
            }
            result.add(row);
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2889 (Reshape Data: Pivot)?

This page provides optimized solutions for LeetCode problem 2889 (Reshape Data: Pivot) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2889 (Reshape Data: Pivot)?

The time complexity for LeetCode 2889 (Reshape Data: Pivot) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2889 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2889 in Java, C++, or Python.

Back to LeetCode Solutions