LeetCode 2889: Reshape Data: Pivot
Problem Description
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.
- 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.
- Iterate through the input data and populate this map.
- 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
:
Solutions
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;
}
}
Loading editor...