#1907

Count Salary Categories

Medium
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

This approach uses a single SQL query with conditional aggregation to count the accounts in each category in one go. This is efficient and concise.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a single SELECT statement with conditional aggregation.
  2. 2Step 2: Use CASE statements to categorize incomes into Low, Average, and High.
  3. 3Step 3: Count the number of accounts for each category in the same query.
  4. 4Step 4: Return the result table with counts for each category.
solution.py10 lines
1# Full working Python code
2SELECT
3    CASE
4        WHEN income < 20000 THEN 'Low Salary'
5        WHEN income BETWEEN 20000 AND 50000 THEN 'Average Salary'
6        ELSE 'High Salary'
7    END AS category,
8    COUNT(*) AS accounts_count
9FROM Accounts
10GROUP BY category;

Complexity note: The complexity remains O(n) since we are still processing each row once, but we are doing it in a more efficient way with a single query.

  • 1Using conditional aggregation can simplify counting in SQL.
  • 2Understanding how to categorize data efficiently is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.