How to find first and last positions of an element in a sorted array in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Function to find the first and last position of an element in a slice
func findFirstAndLastPosition(arr []int, n int) (int, int) {
    first, last := -1, -1

    // Iterate over the slice
    for i := 0; i < len(arr); i++ {
        if arr[i] != n {
            continue
        }
        if first == -1 {
            first = i
        }
        last = i
    }

    return first, last
}

func main() {
    // Define the slice
    arr := []int{1, 7, 3, 3, 3, 3, 1, 9, 18}
    n := 3

    // Call the function
    first, last := findFirstAndLastPosition(arr, n)

    // Output results
    if first != -1 {
        fmt.Printf("First position = %d, Last position = %d\n", first, last)
    } else {
        fmt.Println("Not found")
    }
}

 
 
/*
run:

First position = 2, Last position = 5
 
*/

 



answered 5 days ago by avibootz
...