0
0
Kotlinprogramming~5 mins

Range operator (..) and in operator in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Range operator (..) and in operator
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
101 comparison
1001 comparison
10001 comparison

Pattern observation: The number of operations stays the same no matter how big the range is.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how simple operations like range checks work helps you explain efficiency clearly and confidently in interviews.

Self-Check

"What if we checked if a number is in a list instead of a range? How would the time complexity change?"