Error response format in Rest API - Time & Space Complexity
When a REST API sends an error response, it often builds a structured message. We want to understand how the time to create this error message changes as the error details grow.
How does the work to prepare the error response grow with the size of the error information?
Analyze the time complexity of the following code snippet.
function createErrorResponse(errors) {
const response = { status: "error", errors: [] };
for (const err of errors) {
response.errors.push({ code: err.code, message: err.message });
}
return response;
}
This code builds an error response object by looping over a list of error details and adding each to the response.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of errors to add each error detail to the response.
- How many times: Once for each error in the input list.
As the number of errors increases, the code adds more items to the response one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions to the errors array |
| 100 | About 100 additions to the errors array |
| 1000 | About 1000 additions to the errors array |
Pattern observation: The work grows directly with the number of errors; doubling errors doubles the work.
Time Complexity: O(n)
This means the time to create the error response grows in a straight line with the number of errors.
[X] Wrong: "Adding more errors won't affect the time much because it's just one response."
[OK] Correct: Each error detail is added one by one, so more errors mean more work and more time.
Understanding how error responses scale helps you design APIs that handle many errors efficiently and predict how your code behaves as input grows.
What if we changed the error list to a nested structure with sub-errors? How would the time complexity change?