0
0
Rest APIprogramming~5 mins

Error response structure in Rest API - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Error response structure
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 map operations
100100 map operations
10001000 map operations

Pattern observation: The number of operations grows directly with the number of errors; doubling errors doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to build the error response grows in a straight line with the number of errors.

Common Mistake

[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.

Interview Connect

Understanding how error response time grows helps you design APIs that handle many errors efficiently and predict performance.

Self-Check

"What if the error response included nested details for each error? How would the time complexity change?"