Ternary conditional operator in Swift - Time & Space Complexity
We want to see how the time needed to run code with a ternary conditional operator changes as input size grows.
Does using this operator affect how long the program takes when inputs get bigger?
Analyze the time complexity of the following code snippet.
let number = 10
let result = number % 2 == 0 ? "Even" : "Odd"
print(result)
This code checks if a number is even or odd using the ternary conditional operator and prints the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single conditional check using the ternary operator.
- How many times: Exactly once, no loops or repeated steps.
Since the code runs just one check, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run the code stays constant, no matter how big the input is.
[X] Wrong: "Using the ternary operator makes the code slower as input grows because it's a conditional."
[OK] Correct: The ternary operator only does one check and does not repeat, so input size does not affect its speed.
Understanding that simple conditional checks like the ternary operator run in constant time helps you explain code efficiency clearly and confidently.
"What if we used the ternary operator inside a loop that runs n times? How would the time complexity change?"