Error codes for machine consumption in Rest API - Time & Space Complexity
When APIs return error codes for machines to read, it is important to know how the processing time changes as more errors or requests happen.
We want to understand how the time to handle error codes grows when the number of requests increases.
Analyze the time complexity of the following code snippet.
// Example: Handling error codes in API responses
function handleErrors(errors) {
for (let i = 0; i < errors.length; i++) {
logError(errors[i].code);
}
}
function logError(code) {
// Simulate logging error code
console.log(`Error code: ${code}`);
}
This code loops through a list of error codes and logs each one for machine consumption.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the error codes array.
- How many times: Once for each error in the list.
As the number of error codes increases, the time to process them grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 logging calls |
| 100 | 100 logging calls |
| 1000 | 1000 logging calls |
Pattern observation: Doubling the number of errors doubles the work.
Time Complexity: O(n)
This means the time to handle error codes grows directly with the number of errors.
[X] Wrong: "Logging error codes takes the same time no matter how many errors there are."
[OK] Correct: Each error code requires a separate action, so more errors mean more work.
Understanding how error handling scales helps you design APIs that respond efficiently as usage grows.
"What if the error codes were grouped and logged once per group instead of individually? How would the time complexity change?"