Multiple filter parameters in Rest API - Time & Space Complexity
When using multiple filter parameters in a REST API, it's important to understand how the processing time changes as the number of filters or data size grows.
We want to know how the time to handle requests grows when more filters or data are involved.
Analyze the time complexity of the following code snippet.
GET /items?color=red&size=medium&brand=acme
// Server-side pseudo-code
function getFilteredItems(filters) {
let results = allItems;
for (const key in filters) {
results = results.filter(item => item[key] === filters[key]);
}
return results;
}
This code filters a list of items by applying each filter parameter one after another.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filtering the list of items for each filter parameter.
- How many times: Once per filter parameter, each time scanning the current list of results.
As the number of items or filters increases, the filtering work grows because each filter scans the current list.
| Input Size (n items) | Approx. Operations (with k filters) |
|---|---|
| 10 | About 10 x k |
| 100 | About 100 x k |
| 1000 | About 1000 x k |
Pattern observation: The total work grows roughly in a straight line with the number of items and filters.
Time Complexity: O(n x k)
This means the time to process grows proportionally with both the number of items and the number of filters.
[X] Wrong: "Adding more filters does not affect performance much because each filter is simple."
[OK] Correct: Each filter scans the current list, so more filters mean more repeated scanning, increasing total work.
Understanding how multiple filters affect performance helps you design efficient APIs and explain trade-offs clearly in interviews.
"What if the filters were combined into a single pass instead of multiple passes? How would the time complexity change?"