Search code examples
arraysgoindexingpanic

What causes panic: runtime error: index out of range [4] with length 4 even though array is initialized as dynamic array


I have initialized a dynamic array but it shows index out of range.
I have tried giving fixed length also, but it also shows the same error.

Error Description:
panic: runtime error: index out of range [4] with length 4

package main

import "fmt"

func missingNumber(nums []int) int {
    arrSum := 0
    arrLen := len(nums) + 1
    for i := 0; i < arrLen; i++ {
        arrSum += nums[i]
    }
    numSum := arrLen * (arrLen + 1) / 2
    missingNumber := numSum - arrSum
    return missingNumber
}

func main() {
    nums := []int{1, 3, 4, 5}
    result := missingNumber(nums)
    fmt.Println(result)
}

Solution

  • you should change arrLen := len(nums) + 1 to arrLen := len(nums).

    Your array length is 4. the indexes are 0,1,2,3 for this. but when you tried to do arrLen := len(nums) + 1 . the arrlen value is now 5. but you have only 4 element. and from your loop you are trying to get a element that is not present in array. that will give you a runtime error and it will panic.

    this one will work for you:

    package main
    
    import "fmt"
    
    func missingNumber(nums []int) int {
        arrSum := 0
        arrLen := len(nums)
        for i := 0; i < arrLen; i++ {
            arrSum += nums[i]
        }
        m := arrLen + 1
        numSum := m * (m + 1) / 2
        missingNumber := numSum - arrSum
        return missingNumber
    }
    
    func main() {
        nums := []int{1, 3, 4, 5}
        result := missingNumber(nums)
        fmt.Println(result)
    }