Range operator (..) and in operator in Kotlin - Time & Space Complexity
We want to understand how the time it takes to check if a number is within a range changes as the range size grows.
How does using the range operator and the in operator affect the work done by the program?
Analyze the time complexity of the following code snippet.
val n = 100 // example value for n
val range = 1..n
val number = 50
if (number in range) {
println("Number is in the range")
} else {
println("Number is not in the range")
}
This code creates a range from 1 to n and checks if a fixed number is inside that range.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking if the number is within the range using the in operator.
- How many times: This check happens once per program run here.
Since the range is defined by start and end numbers, checking if a number is inside is a simple comparison.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 comparison |
| 100 | 1 comparison |
| 1000 | 1 comparison |
Pattern observation: The number of operations stays the same no matter how big the range is.
Time Complexity: O(1)
This means checking if a number is in a range takes the same amount of time regardless of the range size.
[X] Wrong: "Checking if a number is in a large range takes longer because the range is bigger."
[OK] Correct: The in operator with ranges uses simple comparisons, not loops, so size does not affect time.
Understanding how simple operations like range checks work helps you explain efficiency clearly and confidently in interviews.
"What if we checked if a number is in a list instead of a range? How would the time complexity change?"