Junior — Middle
What is the time complexity of searching for an element in a list implemented via a slice?
sobes.tech AI
Answer from AI
In Go, a slice is a dynamic array that stores elements in a contiguous memory area. Searching for an element by value in a slice requires iterating over the elements, as slices are not indexed by value.
Thus, the time complexity of searching for an element in a slice is O(n), where n is the number of elements in the slice.
Example of searching for an element:
func contains(slice []int, val int) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
Here, in the worst case, all elements need to be checked.