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?"
Practice
Solution
Step 1: Identify the package for web servers
Thenet/httppackage provides tools to create web servers in Go.Step 2: Recognize the function to start the server
http.ListenAndServestarts a server listening on a specified port.Final Answer:
Thenet/httppackage withhttp.ListenAndServe-> Option AQuick Check:
Web server =net/http.ListenAndServe[OK]
- Confusing printing functions with server functions
- Using file operations instead of network functions
- Thinking math package handles networking
Solution
Step 1: Identify the function to open a file for reading
os.Openopens a file in read-only mode and returns a file and error.Step 2: Check the syntax correctness
The syntaxfile, err := os.Open("data.txt")correctly assigns both file and error.Final Answer:
file, err := os.Open("data.txt") -> Option AQuick Check:
Open file for reading = os.Open [OK]
- Using os.Read which does not exist
- Using ioutil.ReadFile which reads whole file, not opens
- Opening file with wrong flags for reading
package main
import "fmt"
func main() {
nums := []int{2, 4, 6}
squares := make(map[int]int)
for _, n := range nums {
squares[n] = n * n
}
fmt.Println(squares)
}Solution
Step 1: Understand the loop and map assignment
The loop goes through each number in nums and assigns squares[n] = n * n.Step 2: Calculate each square value
2*2=4, 4*4=16, 6*6=36, so the map stores these pairs.Final Answer:
map[2:4 4:16 6:36] -> Option BQuick Check:
Squares map = map with keys and squared values [OK]
- Confusing keys and values in map
- Multiplying incorrectly
- Expecting slice output instead of map
package main
import (
"fmt"
"os"
)
func main() {
file := os.Open("file.txt")
defer file.Close()
fmt.Println("File opened")
}Solution
Step 1: Check os.Open usage
os.Openreturns two values: file and error. The code only assigns one variable.Step 2: Identify missing error handling
Without checking error, the program may panic if file does not open.Final Answer:
Missing error check after os.Open -> Option CQuick Check:
Always check error from os.Open [OK]
- Ignoring error returned by os.Open
- Assuming defer is wrong here
- Thinking file path must be absolute always
Solution
Step 1: Reading numbers from a file
os.Openopens the file for reading; then you can scan or read lines.Step 2: Processing and writing results
Loop through numbers, square them, then useos.Createto create output file andWriteStringor similar to write results.Final Answer:
Useos.Opento read, loop to square, andos.CreatewithWriteStringto save -> Option DQuick Check:
File read + process + write = os.Open + loop + os.Create [OK]
- Using fmt.Println for file I/O
- Confusing math.Pow with file reading
- Using network packages for file tasks
Ready to prove it?
Pass the test and this pattern moves unknown
