What is TypeScript - Complexity Analysis
We want to understand how the time it takes to run TypeScript code changes as the code or input grows.
How does the work done by TypeScript programs grow when we add more data or instructions?
Analyze the time complexity of the following code snippet.
function greet(names: string[]): void {
for (const name of names) {
console.log(`Hello, ${name}!`);
}
}
const people = ['Alice', 'Bob', 'Charlie'];
greet(people);
This code prints a greeting for each name in the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each name in the array.
- How many times: Once for each name in the list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings printed |
| 100 | 100 greetings printed |
| 1000 | 1000 greetings printed |
Pattern observation: The work grows directly with the number of names. Double the names, double the greetings.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "The loop runs the same time no matter how many names there are."
[OK] Correct: More names mean more times the loop runs, so it takes longer.
Understanding how loops affect time helps you explain how your code handles bigger data, a key skill in programming.
"What if we changed the array to a nested array and looped inside loops? How would the time complexity change?"