0
0
Typescriptprogramming~5 mins

Global augmentation in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Global augmentation
O(1)
Understanding Time Complexity

We want to understand how adding new properties or methods to existing types affects the speed of our program.

How does this change the work the program does as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Add a new method to the Array type
declare global {
  interface Array {
    doubleLength(): number;
  }
}

Array.prototype.doubleLength = function() {
  return this.length * 2;
};

const arr = [1, 2, 3];
console.log(arr.doubleLength());
    

This code adds a new method to all arrays that returns twice their length.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing the array's length property.
  • How many times: Once per method call, no loops or recursion involved.
How Execution Grows With Input

Since the method only reads the length property and multiplies it, the work stays the same no matter how big the array is.

Input Size (n)Approx. Operations
101 simple operation
1001 simple operation
10001 simple operation

Pattern observation: The work does not increase as the array grows.

Final Time Complexity

Time Complexity: O(1)

This means the method runs in constant time regardless of the array size.

Common Mistake

[X] Wrong: "Adding a method to Array makes all array operations slower because it loops over elements."

[OK] Correct: The added method runs only when called, and if it does not loop, it does not slow down other array operations.

Interview Connect

Understanding how extending built-in types affects performance shows you can think about code design and efficiency together.

Self-Check

"What if the new method loops through all array elements? How would the time complexity change?"