{x}
blog image

Unpopular Books

Solution Explanation for LeetCode 1098: Unpopular Books

This problem requires querying two tables, Books and Orders, to find books that meet specific criteria: sold less than 10 copies in the last year and available for more than one month.

Approach:

The solution uses SQL to perform the query. The key steps are:

  1. Joining the tables: We perform a LEFT JOIN between Books and Orders using book_id. This ensures we include all books, even those without any orders.

  2. Filtering by availability date: We filter out books that have been available for less than one month using the condition available_from < '2019-05-23'. This is because "today" is given as 2019-06-23, and we need books available for more than a month prior.

  3. Calculating total sales in the last year: We use SUM(IF(dispatch_date >= '2018-06-23', quantity, 0)) to calculate the total quantity sold for each book in the last year (from 2018-06-23 to 2019-06-23). The IF statement ensures we only sum quantities from orders within the last year.

  4. Filtering by sales count: We use HAVING SUM(...) < 10 to filter the results to include only books with less than 10 copies sold in the last year.

  5. Selecting the desired columns: Finally, we select book_id and name to return the required information.

MySQL Code:

SELECT book_id, name
FROM
    Books
    LEFT JOIN Orders USING (book_id)
WHERE available_from < '2019-05-23'
GROUP BY 1
HAVING SUM(IF(dispatch_date >= '2018-06-23', quantity, 0)) < 10;

Time Complexity Analysis:

The time complexity of this SQL query depends on the database engine's optimization strategies. However, a reasonable estimate would be O(N log N) or O(N) in the best case, where N is the total number of rows in the Books and Orders tables. The JOIN, GROUP BY, and HAVING operations could involve sorting or hashing, leading to logarithmic or linear time complexity. The exact complexity depends on factors like indexing and database implementation details. In practice, optimized database systems often handle this type of query efficiently.

Space Complexity Analysis:

The space complexity is primarily determined by the size of the intermediate result sets generated during the query execution. It's proportional to the number of rows that satisfy the conditions of the WHERE and HAVING clauses, which is, at most, the size of the Books table. Therefore, the space complexity is considered to be O(M), where M is the number of books that meet the specified criteria. This is typically less than the total number of books and orders (N) in the database.

This detailed explanation provides a clear understanding of the solution's approach, code implementation, and complexity analysis. Remember that the actual performance might vary slightly based on the specific database system and its configuration.