0
0
Typescriptprogramming~5 mins

Namespace declaration in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Namespace declaration
O(n)
Understanding Time Complexity

When we use namespaces in TypeScript, we group code together. It's important to see how this grouping affects how long the program takes to run.

We want to know: does using namespaces change how the program's speed grows as we add more code inside them?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


namespace MathUtils {
  export function square(n: number): number {
    return n * n;
  }

  export function sum(arr: number[]): number {
    let total = 0;
    for (const num of arr) {
      total += num;
    }
    return total;
  }
}
    

This code defines a namespace with two functions: one squares a number, the other sums an array of numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop inside the sum function that goes through each number in the array.
  • How many times: It runs once for every item in the input array.
How Execution Grows With Input

Explain the growth pattern intuitively.

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

Pattern observation: The time to sum numbers grows directly with how many numbers there are. More numbers mean more additions.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the sum function grows in a straight line with the size of the input array.

Common Mistake

[X] Wrong: "Using a namespace makes the code slower because it adds extra steps."

[OK] Correct: Namespaces only group code logically. They don't add loops or repeated work, so they don't change how long the code takes to run.

Interview Connect

Understanding how code grouping like namespaces affects performance helps you write clear and efficient programs. This skill shows you can think about both organization and speed.

Self-Check

"What if the sum function called another function inside the loop? How would that affect the time complexity?"