Issue
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)
}
Answered By - Emon46 Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.