0
0
Rest APIprogramming~5 mins

Error response format in Rest API - Time & Space Complexity

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

Scenario Under Consideration

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

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

As the number of errors increases, the code adds more items to the response one by one.

Input Size (n)Approx. Operations
10About 10 additions to the errors array
100About 100 additions to the errors array
1000About 1000 additions to the errors array

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

Understanding how error responses scale helps you design APIs that handle many errors efficiently and predict how your code behaves as input grows.

Self-Check

What if we changed the error list to a nested structure with sub-errors? How would the time complexity change?