Junior — Middle
How is the time complexity of searching for an element by value in a slice sequence evaluated?
sobes.tech AI
Answer from AI
The time complexity of searching for an element by value in a slice in Go is O(n), where n is the number of elements in the slice.
This is because a slice is an ordered sequence of elements without an indexed structure for quick search. To find an element, you need to iterate through the slice sequentially, comparing each element with the target value.
Example of searching for an element in a slice:
func contains(slice []int, val int) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
If a faster search is required, consider using data structures with indexed access, such as a map.