package main
import "fmt"
func firstAndLastOccurrence(arr []int, target int) (int, int) {
first := -1
last := -1
for i, val := range arr {
if val == target {
if first == -1 {
first = i // record first occurrence
}
last = i // update last occurrence
}
}
return first, last
}
func main() {
arr := []int{2, 3, 5, 3, 7, 3, 9}
target := 3
first, last := firstAndLastOccurrence(arr, target)
fmt.Printf("List: %v\n", arr)
fmt.Printf("First occurrence of %d at index %d\n", target, first)
fmt.Printf("Last occurrence of %d at index %d\n", target, last)
}
for i, val := range arr {
iterate over each element to check for target
check if current element matches target
if first == -1 { first = i }
record first occurrence only once
update last occurrence whenever target found
List: [2 3 5 3 7 3 9]
First occurrence of 3 at index 1
Last occurrence of 3 at index 5