Lambda expression syntax in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run code with lambda expressions changes as the input grows.
Specifically, how does using a lambda affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
var numbers = new List<int> {1, 2, 3, 4, 5};
var squares = numbers.Select(x => x * x).ToList();
This code creates a list of numbers and uses a lambda expression to create a new list of their squares.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The lambda runs once for each number in the list.
- How many times: Exactly as many times as there are items in the list.
Each number causes one multiplication operation inside the lambda.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the list gets bigger.
[X] Wrong: "Using a lambda makes the code run slower in a way that changes the time complexity."
[OK] Correct: The lambda is just a short way to write a function. It runs once per item, so it does not add extra loops or steps beyond the list size.
Understanding how lambdas work with collections helps you explain code efficiency clearly and confidently in interviews.
"What if the lambda expression called another method that itself loops over the list? How would the time complexity change?"