Error response structure in Rest API - Time & Space Complexity
When a REST API sends an error response, it usually builds a structured message to explain what went wrong.
We want to understand how the time to create this error message changes as the error details grow.
Analyze the time complexity of the following code snippet.
function createErrorResponse(errors) {
return {
status: "error",
errors: errors.map(err => ({ code: err.code, message: err.message }))
};
}
This code builds an error response object by mapping over a list of error details.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Mapping over the errors array to create a new array of error objects.
- How many times: Once for each error in the input list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 map operations |
| 100 | 100 map operations |
| 1000 | 1000 map operations |
Pattern observation: The number of operations grows directly with the number of errors; doubling errors doubles work.
Time Complexity: O(n)
This means the time to build the error response grows in a straight line with the number of errors.
[X] Wrong: "Creating the error response takes the same time no matter how many errors there are."
[OK] Correct: Each error detail must be processed, so more errors mean more work and more time.
Understanding how error response time grows helps you design APIs that handle many errors efficiently and predict performance.
"What if the error response included nested details for each error? How would the time complexity change?"