Case-Insensitive Substring Search Across a Music Catalog
StringsAuto-graded · 23 test casesLast updated
Tests ability to normalize user input and apply multi-field substring filtering across a collection of structured records.
Problem
You are building a search feature for a music streaming service. The service maintains a catalog of tracks, where each track is represented as a dictionary with three string fields: title, author, and genre.
Implement a function search_tracks that takes the catalog and a search term, then returns every track that matches the search term.
Matching Rules
- Comparison must be case-insensitive. A search for
"rock"should match"Rock","ROCK", and"rock"equally. - A match occurs when the search term appears as a contiguous substring in any of the three fields —
title,author, orgenre. - Strip all leading and trailing whitespace from the search term before doing anything else. Inner whitespace (spaces between words) is kept as-is and treated as part of the literal string to find.
- If the search term is empty after stripping — including a term made up entirely of whitespace — return every track in the catalog, preserving the original order.
- A track that matches should appear exactly once in the result, regardless of how many of its fields contain the search term.
Constraints
- The catalog contains between
0and10,000tracks. - The search term has length between
0and100characters. - All field values are non-null strings.
- The relative order of tracks in the output must match their order in the input catalog.
Examples
Example 1
Input: search_tracks([{'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'genre': 'Classic'}, {'title': 'Art of War', 'author': 'Sun Tzu', 'genre': 'Philosophy'}], 'art')
Output: [{'title': 'Art of War', 'author': 'Sun Tzu', 'genre': 'Philosophy'}]
Example 2
Input: search_tracks([{'title': 'The Hobbit', 'author': 'J.R.R. Tolkien', 'genre': 'Fantasy'}, {'title': 'Pride and Prejudice', 'author': 'Jane Austen', 'genre': 'Classic'}], ' FANTASY ')
Output: [{'title': 'The Hobbit', 'author': 'J.R.R. Tolkien', 'genre': 'Fantasy'}]
Example 3
Input: search_tracks([{'title': 'Dune', 'author': 'Frank Herbert', 'genre': 'Science Fiction'}], ' ')
Output: [{'title': 'Dune', 'author': 'Frank Herbert', 'genre': 'Science Fiction'}]
Hints
Hint 1
Normalize the search term exactly once before the loop — strip whitespace first, then convert to a consistent case. Doing it inside the loop wastes work and invites mistakes.
Hint 2
Python's `in` operator performs a literal substring check, so you don't need any regex machinery. Just casefold both the needle and each field value before comparing.
Hint 3
Use `any(...)` over the three fields for each track. It short-circuits on the first match, so a track is never added more than once even if multiple fields match.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is a single linear scan with a pre-normalized search term.
Step by step
1. Normalize once.
Call strip() on the query to remove surrounding whitespace, then casefold() to convert it to a canonical lowercase form. casefold() is stricter than lower() — it handles characters like the German ß correctly — and it's the right tool whenever you need caseless comparison rather than just display formatting.
2. Handle the empty query early.
If the normalized needle is an empty string, no filtering should happen and the whole catalog is returned. Returning catalog[:] (a shallow copy) is safer than returning the list directly, because it prevents callers from accidentally mutating the original through the returned reference.
3. Scan and filter.
For each track, check whether the needle is a substring of any of the three casefolded fields. any(...) over the tuple ("title", "author", "genre") short-circuits on the first match, so a track can never be added to the result more than once even when several fields all contain the needle.
4. Preserve order. A list comprehension iterates the catalog in order and appends only matching tracks, so the relative order of results always matches the input.
Why each rule is satisfied
| Rule | How it's covered |
|---|---|
| Case-insensitive | Both needle and field values are casefolded before in |
| Substring match | Python's in operator performs a literal substring check |
| Strip whitespace | strip() runs before any comparison |
| Empty → return all | Early return on not needle |
| No duplicates | any() short-circuits; a track appears at most once |
A common mistake worth calling out
If you loop over fields and append a matching track inside each field's branch, the same track can end up in the result list multiple times (once per matching field). Using any() at the track level — not the field level — avoids this entirely.
Complexity
- N = number of tracks, L = maximum field length, Q = query length.
- Time: O(N · L) per query in practice. CPython's
inuses an optimized substring algorithm that runs in O(L + Q) per field, and we check at most three fields per track. - Space: O(N) for the output list. Each casefolded field string is a short-lived temporary object.
Edge cases
| Scenario | Result |
|---|---|
| Empty catalog | Returns [] |
Query is "" or " " | Returns a copy of the full catalog |
Query with inner spaces (e.g. "of war") | Treated as a literal sequence; spaces must be present in the field |
| Query longer than every field | No matches, returns [] |
Special characters (".", "(") | Treated literally — in never interprets regex patterns |
Reference solution
from typing import Dict, List
def search_tracks(catalog: List[Dict[str, str]], query: str) -> List[Dict[str, str]]:
needle = query.strip().casefold()
if not needle:
return catalog[:]
return [
track for track in catalog
if any(needle in track[field].casefold() for field in ("title", "author", "genre"))
]