Problem
Table: Emails
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
Write a solution to find all unique email domains and count the number of individuals associated with each domain. Consider only those domains that end with .com.
Return the result table orderd by email domains inascending order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – SQL String Functions and Group By
Intuition
We need to extract the domain from each email, filter for domains ending with .com
, and count the number of unique users for each domain. This can be done using SQL string functions and grouping.
Approach
- Use
SUBSTRING_INDEX(email, '@', -1)
to extract the domain from the email. - Filter for domains ending with
.com
usingLIKE '%.com'
. - Group by the domain and count the number of users for each domain.
- Order the result by domain in ascending order.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the number of emails, as each email is processed once. - 🧺 Space complexity:
O(n)
, for storing the result set and intermediate columns.