0
0
Cybersecurityknowledge~5 mins

Input validation and sanitization in Cybersecurity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Input validation and sanitization
O(n)
Understanding Time Complexity

When checking user input for safety, the time it takes to validate and clean data matters.

We want to know how the work grows as input size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function sanitizeInput(input) {
  let clean = "";
  for (let i = 0; i < input.length; i++) {
    if (input[i] === '<' || input[i] === '>') {
      clean += '';
    } else {
      clean += input[i];
    }
  }
  return clean;
}

This code removes certain characters from the input to prevent harmful data.

Identify Repeating Operations
  • Primary operation: Looping through each character of the input string.
  • How many times: Once for every character in the input.
How Execution Grows With Input

As the input gets longer, the code checks each character one by one.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The work grows directly with input size; double the input means double the checks.

Final Time Complexity

Time Complexity: O(n)

This means the time to clean input grows in a straight line with the input length.

Common Mistake

[X] Wrong: "Sanitizing input takes the same time no matter how long the input is."

[OK] Correct: The code checks each character, so longer input means more work and more time.

Interview Connect

Understanding how input size affects validation helps you write secure and efficient code in real projects.

Self-Check

"What if we used a built-in function that removes all unwanted characters at once? How would the time complexity change?"