Article Views I — LeetCode #1148 (Easy)
Tags: Database
Related patterns: Hash Map, Array
Brute Force approach
Time complexity: O(n²). Space complexity: O(1).
In the brute-force approach, we will check each article's views and see if the author is also a viewer. This is straightforward but inefficient, as it requires checking every view for every article.
The time complexity is O(n²) because for each row, we are checking against all other rows to see if the author viewed their own article, leading to a nested iteration.
- Step 1: Iterate through each row in the Views table.
- Step 2: For each row, check if the author_id is the same as the viewer_id.
- Step 3: If they match, add the author_id to a result set to avoid duplicates.
- Step 4: After processing all rows, sort the result set in ascending order.
- Step 5: Return the sorted result set.
1. Row 1: author_id = 3, viewer_id = 5 (no match)
2. Row 2: author_id = 3, viewer_id = 6 (no match)
3. Row 3: author_id = 7, viewer_id = 7 (match, add 7)
4. Row 4: author_id = 7, viewer_id = 6 (no match)
5. Row 5: author_id = 7, viewer_id = 1 (no match)
6. Row 6: author_id = 4, viewer_id = 4 (match, add 4)
Final result: [4, 7]
Optimal Solution approach
Time complexity: O(n). Space complexity: O(n).
In the optimal solution, we can directly filter the rows where the author is also the viewer in a single pass, making it much more efficient.
The time complexity is O(n) because we only need to scan through the rows once to find matches, and the space complexity is O(n) due to storing unique author_ids.
- Step 1: Use a SELECT statement to filter rows where author_id equals viewer_id.
- Step 2: Use DISTINCT to ensure that we only get unique author_ids.
- Step 3: Sort the results by author_id in ascending order.
1. Row 1: author_id = 3, viewer_id = 5 (no match)
2. Row 2: author_id = 3, viewer_id = 6 (no match)
3. Row 3: author_id = 7, viewer_id = 7 (match, add 7)
4. Row 4: author_id = 7, viewer_id = 6 (no match)
5. Row 5: author_id = 7, viewer_id = 1 (no match)
6. Row 6: author_id = 4, viewer_id = 4 (match, add 4)
Final result: [4, 7]
Key Insights
- Authors can only view their own articles if their author_id matches their viewer_id.
- Using DISTINCT helps in eliminating duplicate entries in the result.
Common Mistakes
- Not using DISTINCT, leading to duplicate author_ids in the result.
- Forgetting to sort the result set before returning.
Interview Tips
- Always clarify the requirements before jumping into coding.
- Think about edge cases, such as no authors viewing their own articles.
- Practice writing SQL queries to become familiar with syntax and logic.