0
0
Goprogramming~5 mins

Relational operators in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Relational operators
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

Each number in the list is checked once, so the work grows directly with the list size.

Input Size (n)Approx. Operations
1010 comparisons
100100 comparisons
10001000 comparisons

Pattern observation: Doubling the input doubles the number of comparisons.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items checked.

Common Mistake

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

Interview Connect

Understanding how simple comparisons scale helps you explain efficiency clearly and shows you know how loops affect performance.

Self-Check

"What if we added a nested loop to compare every number with every other number? How would the time complexity change?"