#3642

Find Books with Polarized Opinions

Medium
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a single pass to track ratings for each book, allowing us to determine polarized opinions efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a dictionary to track the highest and lowest ratings for each book.
  2. 2Step 2: Iterate through reading_sessions and update the ratings in the dictionary.
  3. 3Step 3: Filter books that have at least one rating >= 4 and one rating <= 2.
solution.py1 lines
1SELECT book_id FROM (SELECT book_id, MAX(session_rating) AS max_rating, MIN(session_rating) AS min_rating FROM reading_sessions GROUP BY book_id) AS ratings WHERE max_rating >= 4 AND min_rating <= 2;

Complexity note: We only traverse the reading_sessions once and use a dictionary to store results, leading to linear time complexity.

  • 1Books need both high and low ratings to be considered polarized.
  • 2Using aggregation functions helps simplify the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.