Invalid Tweets II Problem
#3150
Description
LeetCode Problem 3150.
Table: Tweets
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| tweet_id | int |
| content | varchar |
+----------------+---------+
tweet_id is the primary key (column with unique values) for this table.
This table contains all the tweets in a social media app.
Write a solution to find invalid tweets. A tweet is considered invalid if it meets any of the following criteria:
- It exceeds
140characters in length. - It has more than
3mentions. - It includes more than
3hashtags.
Return the result table ordered by tweet_id in ascending order.
The result format is in the following example.
Example:
Input:
Tweets table:
+----------+-----------------------------------------------------------------------------------+
| tweet_id | content |
+----------+-----------------------------------------------------------------------------------+
| 1 | Traveling, exploring, and living my best life @JaneSmith @SaraJohnson @LisaTaylor |
| | @MikeBrown #Foodie #Fitness #Learning |
| 2 | Just had the best dinner with friends! #Foodie #Friends #Fun |
| 4 | Working hard on my new project #Work #Goals #Productivity #Fun |
+----------+-----------------------------------------------------------------------------------+
Output:
+----------+
| tweet_id |
+----------+
| 1 |
| 4 |
+----------+
Explanation:
- tweet_id 1 contains 4 mentions.
- tweet_id 4 contains 4 hashtags.
Output table is ordered by tweet_id in ascending order.
Solution
Approach: Count the characters
All three rules can be checked on the text of the tweet alone, so no join or grouping is needed.
- Length:
CHAR_LENGTH(content) > 140. UseCHAR_LENGTH, notLENGTH, becauseLENGTHcounts bytes and would over-count non-ASCII characters. - Mentions and hashtags: the number of
@signs is the length of the text minus its length with all@removed. The same trick counts#. - A tweet is invalid if any of the three conditions holds, hence the
OR.
In Pandas, str.count("@") and str.count("#") do the counting directly.
SELECT tweet_id
FROM Tweets
WHERE CHAR_LENGTH(content) > 140
OR CHAR_LENGTH(content) - CHAR_LENGTH(REPLACE(content, '@', '')) > 3
OR CHAR_LENGTH(content) - CHAR_LENGTH(REPLACE(content, '#', '')) > 3
ORDER BY tweet_id;