0
0
Terraformcloud~5 mins

For expressions for transformation in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For expressions for transformation
O(n)
Understanding Time Complexity

We want to understand how the time to run a Terraform for expression changes as the input list grows.

Specifically, how does the number of operations grow when transforming a list with a for expression?

Scenario Under Consideration

Analyze the time complexity of this Terraform for expression.


locals {
  input_list = [1, 2, 3, 4, 5]
  output_list = [for item in local.input_list : item * 2]
}
    

This code takes each number in the input list and multiplies it by 2, creating a new list.

Identify Repeating Operations

Look at what repeats as the input list grows.

  • Primary operation: Multiplying each item by 2 (one operation per item).
  • How many times: Once for each item in the input list.
How Execution Grows With Input

As the input list gets bigger, the number of multiplications grows at the same rate.

Input Size (n)Approx. Operations
1010 multiplications
100100 multiplications
10001000 multiplications

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the transformation grows in direct proportion to the input list size.

Common Mistake

[X] Wrong: "The for expression runs in constant time no matter how big the list is."

[OK] Correct: Each item must be processed once, so more items mean more work and more time.

Interview Connect

Understanding how simple transformations scale helps you reason about Terraform configurations and their efficiency in real projects.

Self-Check

"What if the for expression included a nested for expression inside it? How would the time complexity change?"