Practical use cases in Go - Time & Space 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.
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 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.
As the list gets bigger, the time to find the max grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means if you double the list size, the time to find the max roughly doubles too.
[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.
Understanding how your code grows with input size shows you think about efficiency, a key skill in programming.
"What if we sorted the list first? How would the time complexity change when finding the max?"