Sponsored
Sponsored
This approach involves iterating over the list of accounts, checking each account's income against the defined salary ranges, and incrementing counters for each category accordingly. The final step is to return a list or dictionary of these counts for each category.
Time Complexity: O(n), where n is the number of accounts.
Space Complexity: O(1), as no additional space other than a few variables is used.
1
The code defines a function countSalaryCategories
that takes a 2D array accounts
and its size as arguments. The function initializes three counters for low, average, and high salary categories. It iterates over the list of accounts, checking each account's income against the salary ranges, and increments the respective counter. Finally, it prints the counts in a formatted table.
This approach leverages data aggregation methods available in different languages, such as Java's streams, or Python's `collections` library to group and count salary categories, aiming for a more functional programming approach.
Time Complexity: O(n), stemming from the sequential stream processing.
Space Complexity: O(m), where m is the number of unique salary categories, as it stores results in a map.
1import java.util.Arrays;
2import java.util.Map;
3import java.util.function.Function;
4import java.util.stream.Collectors;
5
6public class Main {
7
8 public static void main(String[] args) {
9 int[][] accounts = {{3, 108939}, {2, 12747}, {8, 87709}, {6, 91796}};
10
11 Map<String, Long> categoryCounts = Arrays.stream(accounts)
12 .map(account -> {
13 int income = account[1];
14 if (income < 20000) return "Low Salary";
15 else if (income <= 50000) return "Average Salary";
16 else return "High Salary";
17 })
18 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
19
20 System.out.println("+----------------+----------------+");
21 System.out.println("| category | accounts_count |");
22 System.out.println("+----------------+----------------+");
23 System.out.printf("| Low Salary | %d |\n", categoryCounts.getOrDefault("Low Salary", 0L));
24 System.out.printf("| Average Salary | %d |\n", categoryCounts.getOrDefault("Average Salary", 0L));
25 System.out.printf("| High Salary | %d |\n", categoryCounts.getOrDefault("High Salary", 0L));
26 System.out.println("+----------------+----------------+");
27 }
28}
This Java implementation utilizes streams to categorize the salary of each account into either "Low Salary", "Average Salary", or "High Salary". The stream elements are grouped and counted using Collectors.groupingBy()
and Collectors.counting()
. Missing categories are handled by default values when fetched from the map.