Strict configuration objects in Typescript - Time & Space Complexity
We want to understand how the time it takes to check a strict configuration object grows as the object gets bigger.
How does the program's work increase when more settings are added?
Analyze the time complexity of the following code snippet.
function validateConfig(config: Record, schema: Record): boolean {
for (const key in schema) {
if (!(key in config)) return false;
if (typeof config[key] !== schema[key]) return false;
}
return true;
}
This code checks if a config object matches a strict schema by verifying each required key and its type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each key in the schema object.
- How many times: Once for every key in the schema.
As the number of keys in the schema grows, the number of checks grows at the same pace.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 key checks |
| 100 | About 100 key checks |
| 1000 | About 1000 key checks |
Pattern observation: The work grows directly with the number of keys; doubling keys doubles the checks.
Time Complexity: O(n)
This means the time to validate grows in a straight line with the number of keys in the schema.
[X] Wrong: "Checking each key is constant time no matter how many keys there are."
[OK] Correct: Each key must be checked one by one, so more keys mean more work, not the same amount.
Understanding how validation scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if the schema included nested objects and the validation checked those recursively? How would the time complexity change?"