Go Program to Find Smallest Element in Slice
for loop with if to compare and update it, like: min := slice[0]; for _, v := range slice { if v < min { min = v } }.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func main() { nums := []int{3, 1, 4, 1, 5} if len(nums) == 0 { fmt.Println("Slice is empty") return } min := nums[0] for _, v := range nums { if v < min { min = v } } fmt.Println(min) }
Dry Run
Let's trace the slice [3, 1, 4, 1, 5] through the code
Initialize min
min = 3 (first element)
Compare with 3
3 < 3? No, min stays 3
Compare with 1
1 < 3? Yes, min updated to 1
Compare with 4
4 < 1? No, min stays 1
Compare with 1
1 < 1? No, min stays 1
Compare with 5
5 < 1? No, min stays 1
Return min
min = 1
| Iteration | Current Value | min |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 1 | 1 |
| 3 | 4 | 1 |
| 4 | 1 | 1 |
| 5 | 5 | 1 |
Why This Works
Step 1: Start with first element
We assume the first element is the smallest to have a starting point for comparison.
Step 2: Loop through slice
We check each element to see if it is smaller than the current smallest.
Step 3: Update smallest value
If a smaller element is found, we update our smallest value to that element.
Alternative Approaches
package main import ( "fmt" "sort" ) func main() { nums := []int{3, 1, 4, 1, 5} if len(nums) == 0 { fmt.Println("Slice is empty") return } sort.Ints(nums) fmt.Println(nums[0]) }
package main import "fmt" func findMin(nums []int) int { if len(nums) == 1 { return nums[0] } minRest := findMin(nums[1:]) if nums[0] < minRest { return nums[0] } return minRest } func main() { nums := []int{3, 1, 4, 1, 5} if len(nums) == 0 { fmt.Println("Slice is empty") return } fmt.Println(findMin(nums)) }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so it runs in linear time proportional to the slice size.
Space Complexity
It uses a fixed amount of extra space regardless of input size, so space complexity is constant.
Which Approach is Fastest?
The single loop approach is fastest because it only scans once. Sorting is slower (O(n log n)) and recursion uses extra memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Single loop | O(n) | O(1) | Fastest and simplest for finding smallest |
| Sorting | O(n log n) | O(1) | When you also need sorted data |
| Recursion | O(n) | O(n) | Elegant but uses more memory |