How to search insert position of K in a sorted array with Go

2 Answers

0 votes
// Given a sorted array/vector/list of distinct integers and a target value K, 
// return the index if the target is found. 
// If not, return the index where it would be if it were inserted in order.

package main

import "fmt"

// Function to find the index of k or the position where it should be inserted
func searchInsertPositionOfK(arr []int, k int) int {
    for i := 0; i < len(arr); i++ {
        // If k is found or needs to be inserted before arr[i]
        if arr[i] >= k {
            return i
        }
    }
    // If k is greater than all elements, it should be inserted at the end
    return len(arr)
}

func main() {
    arr1 := []int{1, 3, 5, 6, 7, 8}
    k1 := 5
    fmt.Println(searchInsertPositionOfK(arr1, k1))

    arr2 := []int{1, 3, 5, 6, 7, 8}
    k2 := 2
    fmt.Println(searchInsertPositionOfK(arr2, k2))

    arr3 := []int{1, 3, 5, 6, 7, 8}
    k3 := 9
    fmt.Println(searchInsertPositionOfK(arr3, k3))
}

 
/*
run:

2
1
6
 
*/

 



answered May 10, 2025 by avibootz
0 votes
// Given a sorted array/vector/list of distinct integers and a target value K, 
// return the index if the target is found. 
// If not, return the index where it would be if it were inserted in order.

package main

import "fmt"

// Function to find the index of k or the position where it should be inserted - Using Binary Search
func searchInsertPositionOfK(arr []int, k int) int {
    left, right := 0, len(arr)-1

    for left <= right {
        mid := left + (right-left)/2

        if arr[mid] == k {
            return mid
        } else if arr[mid] > k {
            right = mid - 1
        } else {
            left = mid + 1
        }
    }

    // If k is not found, return the index where it should be inserted
    return left
}

func main() {
    arr1 := []int{1, 3, 5, 6, 7, 8}
    k1 := 5
    fmt.Println(searchInsertPositionOfK(arr1, k1))

    arr2 := []int{1, 3, 5, 6, 7, 8}
    k2 := 2
    fmt.Println(searchInsertPositionOfK(arr2, k2))

    arr3 := []int{1, 3, 5, 6, 7, 8}
    k3 := 9
    fmt.Println(searchInsertPositionOfK(arr3, k3))
}


 
/*
run:

2
1
6
 
*/

 



answered May 10, 2025 by avibootz
...