0
0
Typescriptprogramming~5 mins

Equality narrowing in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Equality narrowing
O(1)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when we use equality narrowing in TypeScript.

Specifically, we ask: how does checking equality affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processValue(x: string | number) {
  if (x === 42) {
    return "The answer";
  } else if (x === "hello") {
    return "Greeting";
  } else {
    return "Unknown";
  }
}
    

This code checks if the input matches specific values and returns a result based on that.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A few equality checks (comparisons) done one after another.
  • How many times: Each check happens once per function call, no loops or repeated traversals.
How Execution Grows With Input

Since the code only does a fixed number of checks, the time does not grow with input size.

Input Size (n)Approx. Operations
102 checks
1002 checks
10002 checks

Pattern observation: The number of operations stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays constant no matter the input size.

Common Mistake

[X] Wrong: "More input values mean more time because the checks will repeat for each possible value."

[OK] Correct: The code only checks a fixed number of values once, so input size does not affect the number of checks.

Interview Connect

Understanding how simple equality checks work helps you explain how your code runs efficiently and why some checks don't slow down your program as input grows.

Self-Check

"What if we added a loop to check the input against many values? How would the time complexity change?"