Validation error details in Rest API - Time & Space Complexity
When a REST API checks data for errors, it often validates each input field.
We want to know how the time to find errors grows as the number of fields increases.
Analyze the time complexity of the following code snippet.
// Validate each field in the input data
for (const field of inputFields) {
if (!isValid(field)) {
errors.push({ field, message: 'Invalid value' });
}
}
return errors;
This code checks each input field one by one and collects error messages for invalid fields.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each input field to validate it.
- How many times: Once for every field in the input list.
As the number of input fields grows, the number of validations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 validations |
| 100 | 100 validations |
| 1000 | 1000 validations |
Pattern observation: The work grows directly with the number of fields; double the fields, double the checks.
Time Complexity: O(n)
This means the time to find validation errors grows in a straight line with the number of input fields.
[X] Wrong: "Validation time stays the same no matter how many fields there are."
[OK] Correct: Each field needs to be checked, so more fields mean more work and more time.
Understanding how validation scales helps you design APIs that handle many inputs efficiently and predict performance.
"What if the validation function itself loops through a list inside each field? How would the time complexity change?"