Fix the Broken Search Filter in a Book Catalog API
InstacartBackend Engineer · Online AssessmentLast updated
This problem tests your ability to sanitize inputs and implement robust filtering logic on a collection of structured objects using multiple criteria.
Problem Statement
You are building a backend search service for a bookstore catalog. You are given a list of books, where each book is a dictionary with title, author, and genre fields. Your task is to implement a filter_books function that returns a list of books matching a search query.
Requirements:
- The search query should be case-insensitive.
- The search query should be checked against the
title,author, andgenrefields. - The search query should be matched as a substring (i.e., if the query is "art", a book with genre "Fantasy" would be a match if it contained the sequence "art").
- You must trim leading and trailing whitespace from the search query before performing the search.
- If the search query is empty (after trimming), return all books in the catalog.
Function Signature:
def filter_books(catalog, query):
# catalog: list of dicts [{'title': str, 'author': str, 'genre': str}]
# query: str
# returns: list of dicts
Example:
catalog = [
{'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'genre': 'Classic'},
{'title': 'Art of War', 'author': 'Sun Tzu', 'genre': 'Philosophy'}
]
# Query "art"
# Output: [
# {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'genre': 'Classic'},
# {'title': 'Art of War', 'author': 'Sun Tzu', 'genre': 'Philosophy'}
# ]
# Explanation: "Art" matches the end of "Gatsby" (case-insensitive) and the beginning of "Art of War".
Constraints:
cataloglength is between 0 and 10,000.querylength is between 0 and 100.- Fields are always non-null strings.
Hints
Hint 1
Normalize the search query by applying .strip() and .lower() immediately at the start of the function.
Hint 2
For each book, check if the normalized query exists as a substring in the lowercase version of the title, author, or genre.
Hint 3
Ensure your loop breaks early or uses an 'any' condition to avoid redundant checks once a match is found for a specific book.
Follow-up questions
- How would you modify the function to support an 'AND' search, where all words in the query must appear across the book's metadata?
- If the catalog contained 10 million books, how would you optimize this search to perform better than O(N)?
- How would you handle a scenario where the search query needs to support special characters or regex patterns?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.