0
0
Rest APIprogramming~5 mins

Validation error details in Rest API - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Validation error details
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

As the number of input fields grows, the number of validations grows the same way.

Input Size (n)Approx. Operations
1010 validations
100100 validations
10001000 validations

Pattern observation: The work grows directly with the number of fields; double the fields, double the checks.

Final Time Complexity

Time Complexity: O(n)

This means the time to find validation errors grows in a straight line with the number of input fields.

Common Mistake

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

Interview Connect

Understanding how validation scales helps you design APIs that handle many inputs efficiently and predict performance.

Self-Check

"What if the validation function itself loops through a list inside each field? How would the time complexity change?"