0
0
Typescriptprogramming~5 mins

What is TypeScript - Complexity Analysis

Choose your learning style9 modes available
Time Complexity: What is TypeScript
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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

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

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 greetings printed
100100 greetings printed
10001000 greetings printed

Pattern observation: The work grows directly with the number of names. Double the names, double the greetings.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items.

Common Mistake

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

Interview Connect

Understanding how loops affect time helps you explain how your code handles bigger data, a key skill in programming.

Self-Check

"What if we changed the array to a nested array and looped inside loops? How would the time complexity change?"