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.
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.
1from collections import Counter
2
3def count_salary_categories(accounts):
4 categories = [
5 "Low Salary" if income < 20000 else
6 "Average Salary" if income <= 50000 else
7 "High Salary"
8 for _, income in accounts
9 ]
10
11 category_counts = dict(Counter(categories))
12
13 table_format = (
14 "+----------------+----------------+\n"
15 "| category | accounts_count |\n"
16 "+----------------+----------------+\n"
17 "| Low Salary | {} |\n"
18 "| Average Salary | {} |\n"
19 "| High Salary | {} |\n"
20 "+----------------+----------------+"
21 )
22 print(table_format.format(
23 category_counts.get("Low Salary", 0),
24 category_counts.get("Average Salary", 0),
25 category_counts.get("High Salary", 0)
26 ))
27
28accounts = [(3, 108939), (2, 12747), (8, 87709), (6, 91796)]
29count_salary_categories(accounts)
In this Python approach, a list comprehension categorizes each income, and collections.Counter
counts occurrences for each category in just one pass. Default values of zero are used for categories not present in the result.