1

What is the time complexity of the following function which removes an element from slice?

Is it O(n)? How append function in Go affects time complexity ? (Since following code tries to remove an element the new slice capacity is less than or equal to former slice , i was under the impression that just new slice header only gets created behind the scenes and O(n) would be time complexity).

The slice that gets passed as parameter to function has capacity, length equal.

// Remove a given element from slice 
func Remove(elementToRemove string, elements []string) []string {
    if govalidator.IsNull(elementToRemove) {
        return elements
    }
    for i := len(elements) - 1; i >= 0; i-- {
        if elements[i] == elementToRemove {
            elements = append(elements[:i], elements[i+1:]...)
            break
        }
    }
    return elements
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Mozhi
  • 757
  • 1
  • 11
  • 28
  • The work done by append in your case (cap > len) is proportionally to the size of what gets appended. – Volker Oct 31 '19 at 04:33
  • Does this answer your question? [Big O of append in Golang](https://stackoverflow.com/questions/17332227/big-o-of-append-in-golang) – jidicula Mar 16 '21 at 20:13

0 Answers0