Sponsored
Sponsored
This approach involves using a pivot table strategy to reformat the data. The key is to transform row data of each month's revenue into separate columns for each month. We will iterate through the table, grouping revenues by department id and arranging them into columns corresponding to each month.
Time Complexity: O(n), where n is the number of rows in the input table.
Space Complexity: O(n), for storing the pivoted DataFrame.
1function reformatDepartmentTable(department) {
2 const result = new Map();
3 const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
4
5 department.forEach(({ id, revenue, month }) => {
6 if (!result.has(id)) {
7 result.set(id, { id: id });
8 }
9 result.get(id)[`${month}_Revenue`] = revenue;
10 });
11
12 return Array.from(result.values()).map(record => {
13 months.forEach(month => {
14 if (!record.hasOwnProperty(`${month}_Revenue`)) {
15 record[`${month}_Revenue`] = null;
16 }
17 });
18 return record;
19 });
20}
This JavaScript solution uses a Map to accumulate revenue data by department. It initializes each department with null values for each month which are filled in as revenue data is encountered. Missing months are explicitly set to null before returning the result.
This approach focuses on iterating over the data, storing information using an aggregation map or dictionary. Each department will have its own dictionary that maps months to revenue, allowing us to easily access and format this data into the desired output structure.
Time Complexity: O(n * m), where n is the number of departments and m is the number of months.
Space Complexity: O(n * m), with m fixed at 12, for storing department-month mappings.
1import java.util.*;
2
3
This Java solution uses a HashMap to collect month-specific revenue data for each department. After populating this map, it constructs the output list by iterating over departments, ensuring that all months are represented, inserting null where revenue data is absent.