Problem 1731

Abstract / Summary

Given employee data, list how many direct subordinates each employee has.

Note

The full problem description, including helpful examples, can be found on LeetCode.

MySQL 1731.sql

SELECT m.employee_id,
       m.name,
       COUNT(*) AS reports_count,
       ROUND(AVG(e.age)) AS average_age
  FROM Employees m, Employees e
 WHERE m.employee_id = e.reports_to
 GROUP BY m.employee_id
 ORDER BY m.employee_id
8 lines | 235 bytes | submitted September 7, 2023 | GitHub  

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (700k+ submissions).

Typical patterns to solve this problem:
  • Database
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The query extracts managerial information from an Employees table that stores both employee records and hierarchical relationships. For each manager, identified by employee_id, the statement returns the manager’s identifier, name, the total number of direct reports, and the rounded average age of those reports. The result set is ordered by the manager’s identifier, providing a deterministic sequence.

Key Steps

The first step establishes two aliases for the same table: m represents a potential manager and e represents an employee who may report to that manager. The WHERE clause links the two aliases through the condition m.employee_id = e.reports_to, ensuring that only rows where an employee reports directly to the manager are considered.

FROM Employees m, Employees e
WHERE m.employee_id = e.reports_to

Next, the SELECT list gathers the manager’s identifier and name directly from the m alias. The COUNT(*) aggregate counts every row that satisfies the join condition, yielding the number of direct reports for each manager.

SELECT m.employee_id,
       m.name,
       COUNT(*) AS reports_count,

The AVG(e.age) aggregate computes the mean age of the reports, and ROUND rounds the result to the nearest integer, producing a clean, whole-number average.

ROUND(AVG(e.age)) AS average_age

The GROUP BY clause groups rows by the manager’s identifier, which implicitly groups by the manager’s name as well because the name is functionally dependent on the identifier. This grouping enables the aggregates to be calculated per manager.

GROUP BY m.employee_id

Finally, the ORDER BY clause sorts the output by the manager’s identifier, guaranteeing a predictable ordering of rows.

ORDER BY m.employee_id

Edge Cases Handled

When a manager has no direct reports, the join condition eliminates that manager from the result set because there are no matching rows in the e alias. Consequently, the query naturally excludes managers without reports, avoiding a division-by-zero scenario in the average age calculation.

If an employee’s reports_to column contains a null value, that employee does not satisfy the join condition, and therefore does not affect any manager’s aggregates. This behavior prevents null references from contaminating the counts or averages.

In the event that the age column contains null values for some reports, the AVG function automatically ignores those nulls, ensuring that the average age reflects only known ages. The ROUND function then operates on the resulting non-null average.

Performance Optimizations

The query leverages a self-join on the primary key (employee_id) and the foreign key (reports_to). When an index exists on employee_id (typically the primary key) and an index exists on reports_to, the database engine can efficiently locate matching rows for each manager, reducing the cost of the join operation.

The use of COUNT(*) avoids the overhead of counting a specific column, allowing the engine to use a simple row count during aggregation.

Aggregating directly within the grouped result set (COUNT(*) and AVG(e.age)) eliminates the need for additional subqueries or temporary tables, keeping the execution plan compact.

Sorting is performed on the grouped identifier, which is already the grouping key. Many database systems can produce the grouped rows in sorted order without a separate sorting step, further streamlining the final ordering.

Overall, the query’s structure-simple join, direct aggregation, and ordering on the grouping key-aligns well with typical relational engine optimizations, delivering efficient execution for typical employee hierarchies.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big school where some teachers have students who report to them. This code is like a helper looking through a giant list of everyone in the school. First, it finds the teachers and then looks for all the students who report to each one. Once it matches the students to their teacher, it counts up how many students each teacher has. After that, it takes the ages of all those students and does some math to find out the average age. Finally, it puts all the teachers in order by their identification numbers so the list is neat and tidy.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.48 | σ = 1.37

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC SQL
leetcode.ca SQL
Progiez C++ Java Python
github suxrobGM SQL
AlgoMonster C++, Python, Java, TypeScript
WalkCCC SQL
leetcode.ca SQL
Progiez C++, Java, Python
suxrobGM SQL
10 links | 5 authors | 5 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

29 easy 13 medium
43 solutions   September 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality