0
0
Rest APIprogramming~5 mins

Human-readable error messages in Rest API - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Human-readable error messages
O(n)
Understanding Time Complexity

When creating human-readable error messages in a REST API, it's important to know how the time to generate these messages changes as the number of errors grows.

We want to understand how the work needed to prepare error messages increases with more errors.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def format_errors(errors):
    messages = []
    for error in errors:
        message = f"Error {error['code']}: {error['message']}"
        messages.append(message)
    return messages

This code takes a list of error objects and creates a list of readable error messages.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each error in the list.
  • How many times: Once for each error in the input list.
How Execution Grows With Input

As the number of errors increases, the time to create messages grows in a straight line.

Input Size (n)Approx. Operations
1010 message creations
100100 message creations
10001000 message creations

Pattern observation: Doubling the number of errors doubles the work needed to create messages.

Final Time Complexity

Time Complexity: O(n)

This means the time to create error messages grows directly with the number of errors.

Common Mistake

[X] Wrong: "Creating error messages takes the same time no matter how many errors there are."

[OK] Correct: Each error needs its own message, so more errors mean more work and more time.

Interview Connect

Understanding how error message creation scales helps you write APIs that stay responsive even when many errors occur. This skill shows you can think about performance in real situations.

Self-Check

"What if we combined all error messages into one string instead of a list? How would the time complexity change?"