KatInterview

Case-Insensitive Substring Search Across a Music Catalog

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstringsfilteringcase-insensitive

Last 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

  1. Comparison must be case-insensitive. A search for "rock" should match "Rock", "ROCK", and "rock" equally.
  2. A match occurs when the search term appears as a contiguous substring in any of the three fields — title, author, or genre.
  3. 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.
  4. 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.
  5. 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 0 and 10,000 tracks.
  • The search term has length between 0 and 100 characters.
  • 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.