0
0
Goprogramming~5 mins

Practical use cases in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Practical use cases
O(n)
Understanding Time Complexity

When we write programs, it helps to know how fast they run as the input grows.

This helps us pick the best way to solve a problem in real life.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func findMax(numbers []int) int {
    max := numbers[0]
    for _, num := range numbers {
        if num > max {
            max = num
        }
    }
    return max
}

This code finds the biggest number in a list by checking each number once.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the list.
  • How many times: Once for every number in the list.
How Execution Grows With Input

As the list gets bigger, the time to find the max grows in a straight line.

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

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means if you double the list size, the time to find the max roughly doubles too.

Common Mistake

[X] Wrong: "Since we only want the max, we can skip many numbers and still be fast."

[OK] Correct: To be sure of the max, you must check every number at least once.

Interview Connect

Understanding how your code grows with input size shows you think about efficiency, a key skill in programming.

Self-Check

"What if we sorted the list first? How would the time complexity change when finding the max?"