Sparse fieldsets (select fields) in Rest API - Time & Space Complexity
When using sparse fieldsets in REST APIs, we ask how the time to process a request changes as the number of requested fields grows.
We want to know how selecting fewer or more fields affects the work the server does.
Analyze the time complexity of the following code snippet.
GET /articles?fields[articles]=title,author,date
// Server-side pseudo-code
fields = parseFields(request.query)
result = []
for article in articles:
filtered = {}
for field in fields:
filtered[field] = article[field]
result.append(filtered)
return result
This code selects only requested fields from each article before sending the response.
- Primary operation: Looping over each article and then over each requested field.
- How many times: Outer loop runs once per article (n times), inner loop runs once per requested field (k times).
The total work grows with both the number of articles and the number of fields requested.
| Input Size (articles n, fields k) | Approx. Operations |
|---|---|
| 10 articles, 2 fields | 20 operations |
| 100 articles, 5 fields | 500 operations |
| 1000 articles, 10 fields | 10,000 operations |
Pattern observation: The work grows by multiplying the number of articles by the number of fields requested.
Time Complexity: O(n * k)
This means the time grows proportionally to the number of articles times the number of fields selected.
[X] Wrong: "Selecting fewer fields always makes the request time constant regardless of articles."
[OK] Correct: Even if few fields are selected, the server still processes each article, so time grows with the number of articles.
Understanding how sparse fieldsets affect processing helps you explain API efficiency and scalability clearly in interviews.
"What if the server cached filtered results for common fieldsets? How would that change the time complexity?"