Logical operators in Go - Time & Space Complexity
Logical operators combine true or false values to decide outcomes.
We want to see how using these operators affects how long the program takes as inputs grow.
Analyze the time complexity of the following code snippet.
func checkValues(values []bool) bool {
result := false
for _, v := range values {
result = result || v
}
return result
}
This code checks if any value in a list is true using the logical OR operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list once.
- How many times: Exactly once for each item in the input list.
As the list gets longer, the program checks more values one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Logical operators make the code run instantly regardless of input size."
[OK] Correct: Even with logical operators, the program still checks each item one by one, so time grows with input size.
Understanding how logical operators affect loops helps you explain how your code handles data efficiently.
"What if we stop checking as soon as we find a true value? How would the time complexity change?"