Junior — Middle
How can you efficiently remove an element from a slice without preserving the order of elements, while maintaining constant operation complexity?
sobes.tech AI
Answer from AI
To remove an element from a slice in Go without preserving the order of elements and while having an operation with constant complexity O(1), you can replace the element to be removed with the last element of the slice and then shorten the slice by one.
Example:
func removeUnordered(s []int, i int) []int {
s[i] = s[len(s)-1] // replace element i with the last
return s[:len(s)-1] // shorten the slice
}
// Usage:
s := []int{10, 20, 30, 40, 50}
s = removeUnordered(s, 1) // remove element at index 1 (20)
// Now s could be, for example, [10, 50, 30, 40]
This method does not preserve the order of elements but works very quickly since it does not require shifting elements.