Relational operators in Go - Time & Space Complexity
Relational operators compare values to decide true or false. We want to see how long these comparisons take as input grows.
How does the number of comparisons change when we check many values?
Analyze the time complexity of the following code snippet.
package main
func countGreaterThan(nums []int, threshold int) int {
count := 0
for _, num := range nums {
if num > threshold {
count++
}
}
return count
}
This code counts how many numbers in a list are greater than a given threshold.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One comparison per number using the > operator inside a loop.
- How many times: Once for each number in the input list.
Each number in the list is checked once, so the work grows directly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: Doubling the input doubles the number of comparisons.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items checked.
[X] Wrong: "Relational operators take longer as numbers get bigger."
[OK] Correct: The comparison time is the same no matter the number size; only the count of comparisons matters.
Understanding how simple comparisons scale helps you explain efficiency clearly and shows you know how loops affect performance.
"What if we added a nested loop to compare every number with every other number? How would the time complexity change?"