Logical operators (&&, ||, !) in Ruby - Time & Space Complexity
Logical operators help decide true or false in code. We want to see how using them affects how long the code takes to run.
How does the number of checks grow when we use these operators?
Analyze the time complexity of the following code snippet.
def check_values(a, b, c)
if a && b || !c
return true
else
return false
end
end
This code checks three values using logical AND, OR, and NOT to decide true or false.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Evaluating three logical conditions once each.
- How many times: Each condition is checked only once per call.
Each time the function runs, it checks three values. The number of checks stays the same no matter what.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 checks |
| 10 | 3 checks |
| 100 | 3 checks |
Pattern observation: The number of operations does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the time to run the code stays the same no matter how big the input is.
[X] Wrong: "Logical operators slow down the program a lot when inputs grow."
[OK] Correct: Logical operators here only check a fixed number of values once, so time does not grow with input size.
Understanding how simple checks like logical operators behave helps you explain code efficiency clearly and confidently.
"What if we checked logical operators inside a loop over an array? How would the time complexity change?"