Preconditions (require, check, error) in Kotlin - Time & Space Complexity
We want to understand how the time cost changes when using precondition checks like require, check, and error in Kotlin.
How does adding these checks affect the program's running time as input grows?
Analyze the time complexity of the following code snippet.
fun processList(numbers: List<Int>) {
require(numbers.isNotEmpty()) { "List cannot be empty" }
for (number in numbers) {
check(number > 0) { "Number must be positive" }
println(number)
}
if (numbers.size > 1000) {
error("List too large to process")
}
}
This code checks conditions before and during processing a list of numbers, printing each number if all checks pass.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each number in the list.
- How many times: Once for each item in the list (n times).
The checks outside the loop run once, but the loop runs once per item, so the total work grows as the list gets bigger.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and prints |
| 100 | About 100 checks and prints |
| 1000 | About 1000 checks and prints |
Pattern observation: The time grows directly with the number of items in the list.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the size of the input list.
[X] Wrong: "Precondition checks like require or check add a lot of extra time for every item."
[OK] Correct: These checks run once per item inside the loop, just like any other simple operation, so they add a small constant time per item, not extra loops or nested work.
Understanding how precondition checks affect time helps you write safe code without worrying about slowing down your program too much as inputs grow.
"What if we moved the check(number > 0) outside the loop to run once for the whole list? How would the time complexity change?"