0
0
Kotlinprogramming~5 mins

Array creation and usage in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array creation and usage
O(n)
Understanding Time Complexity

When we create and use arrays, it is important to know how the time to run our code changes as the array size grows.

We want to understand how many steps the program takes when working with arrays of different sizes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun sumArray(arr: IntArray): Int {
    var sum = 0
    for (num in arr) {
        sum += num
    }
    return sum
}

fun main() {
    val numbers = IntArray(5) { it + 1 } // creates [1, 2, 3, 4, 5]
    println(sumArray(numbers))
}
    

This code creates an array of integers and then sums all its elements.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element of the array to add it to the sum.
  • How many times: Exactly once for each element in the array.
How Execution Grows With Input

As the array gets bigger, the program does more additions, one for each element.

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

Pattern observation: The number of steps grows directly with the size of the array.

Final Time Complexity

Time Complexity: O(n)

This means the time to sum the array grows in a straight line as the array gets bigger.

Common Mistake

[X] Wrong: "Creating an array takes no time or is instant regardless of size."

[OK] Correct: Actually, creating an array of size n requires setting up space and often initializing each element, so the time grows with n.

Interview Connect

Understanding how array operations scale helps you explain your code clearly and shows you know how programs behave with bigger data.

Self-Check

"What if we changed the array to a list and used a built-in sum function? How would the time complexity change?"