0
0
Typescriptprogramming~5 mins

The in operator narrowing in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: The in operator narrowing
O(n)
Understanding Time Complexity

We want to see how using the in operator affects the time it takes for a program to run.

Specifically, how checking if a property exists in an object changes the work done as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function process(input: object, keys: string[]) {
  for (const key of keys) {
    if (key in input) {
      console.log(`Found key: ${key}`);
    }
  }
}
    

This code checks each key in an array to see if it exists in the given object.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over the keys array and checking key in input.
  • How many times: Once for each key in the keys array.
How Execution Grows With Input

Each key check takes about the same time, so total work grows as the number of keys grows.

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

Pattern observation: The work increases directly with the number of keys checked.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the number of keys grows.

Common Mistake

[X] Wrong: "Checking if a key exists with in takes longer for bigger objects."

[OK] Correct: Property checks with in are very fast and do not depend on object size because objects use fast lookup methods internally.

Interview Connect

Understanding how property checks scale helps you reason about code efficiency and write better programs.

Self-Check

"What if we replaced the object with a nested object and checked keys deeply? How would the time complexity change?"