Junior — Middle
What is the time complexity of adding an element to the end of a list?
sobes.tech AI
Answer from AI
In C#, the operation of adding an element to the end of a List<T> usually has an amortized time complexity of O(1). This means that, on average, adding occurs in constant time.
However, if the internal array underlying the List<T> is full, it is expanded (elements are copied to a new larger array), which takes O(n) time, where n is the current size of the list.
Therefore, in most cases, adding an element to the end of the list is fast, but occasionally it can be more costly due to memory reallocation.