Reason about invariants and complexity
Reason about invariants and complexity
A loop invariant is a property that holds before and after each iteration. Use it to explain correctness: initialization establishes it, each step preserves it, and termination gives the answer. Complexity describes growth with input size n, not elapsed seconds. O(n) means an asymptotic upper bound proportional to n.
package main
import ( "fmt")
func sum(xs []int) int { total := 0 for _, x := range xs { total += x } return total}func main() { fmt.Println(sum([]int{2, 4, 6}), sum(nil))}After k elements, total is their sum; initially k=0 and total=0. Each step adds the next element. At termination all elements have been processed. Time O(n), auxiliary space O(1), assuming fixed-width arithmetic and sums that fit int.
Expected output:
12 0Count pairs rather than guess timing
package main
import ( "fmt")
func pairs(n int) int { count := 0 for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { count++ } } return count}func main() { fmt.Println(pairs(4), pairs(8))}The inner loop visits every unordered pair exactly once: n(n-1)/2 visits, so time is O(n²). It uses constant extra storage. Doubling input roughly quadruples the work for large n. Counting operations is not benchmarking; avoid assuming exact CPU timings.
Expected output:
6 28Try it locally
Count positive integers in []int{-2,0,3,7,-1}; also handle nil. State the invariant and time bound.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 01: Reason about invariants and complexity
Check the lesson objective before moving on.
What must a loop invariant describe?
What is the growth of visiting every unordered pair?