Array creation and usage in Kotlin - Time & Space 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.
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 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.
As the array gets bigger, the program does more additions, one for each element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the size of the array.
Time Complexity: O(n)
This means the time to sum the array grows in a straight line as the array gets bigger.
[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.
Understanding how array operations scale helps you explain your code clearly and shows you know how programs behave with bigger data.
"What if we changed the array to a list and used a built-in sum function? How would the time complexity change?"