Input validation and sanitization in Cybersecurity - Time & Space 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.
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.
- Primary operation: Looping through each character of the input string.
- How many times: Once for every character in the input.
As the input gets longer, the code checks each character one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with input size; double the input means double the checks.
Time Complexity: O(n)
This means the time to clean input grows in a straight line with the input length.
[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.
Understanding how input size affects validation helps you write secure and efficient code in real projects.
"What if we used a built-in function that removes all unwanted characters at once? How would the time complexity change?"