#1148
Article Views I
EasyDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space 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.
⚙️
Algorithm
3 steps- 1Step 1: Use a SELECT statement to filter rows where author_id equals viewer_id.
- 2Step 2: Use DISTINCT to ensure that we only get unique author_ids.
- 3Step 3: Sort the results by author_id in ascending order.
solution.py4 lines
1SELECT DISTINCT author_id AS id
2FROM Views
3WHERE author_id = viewer_id
4ORDER BY id;ℹ
Complexity note: 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.
- 1Authors can only view their own articles if their author_id matches their viewer_id.
- 2Using DISTINCT helps in eliminating duplicate entries in the result.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.