0
0
Kotlinprogramming~5 mins

Single-expression functions in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Single-expression functions
O(n)
Understanding Time Complexity

We want to see how fast a single-expression function runs as the input size changes.

How does the work inside this short function grow when input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

fun sumList(numbers: List<Int>) = numbers.sum()

This function returns the sum of all numbers in a list using a single-expression style.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The function calls sum() which goes through each number in the list once.
  • How many times: It visits every item in the list exactly one time.
How Execution Grows With Input

As the list gets bigger, the function does more work by adding more numbers.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the size of the list.

Common Mistake

[X] Wrong: "Because the function is one line, it must run instantly no matter the input size."

[OK] Correct: Even a single line can do a lot of work if it processes every item in a list. The length of the list matters more than the number of lines.

Interview Connect

Understanding how simple-looking functions still depend on input size helps you explain your code clearly and think about efficiency in real projects.

Self-Check

"What if we changed the function to return the first item instead of summing all? How would the time complexity change?"