Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O of list resize

This question applies to all languages but let me stick to C#

var names = new List<string> {"Jerry", "Cosmo", "Elaine", "George"};

This is my compile time list. If I decide to insert record into it, then .Net underneath doubles the length from 4 to 8.

names.Insert("Newman");

Does Big-O of this insert method above become O(N)? Where N as length of the list? If yes, do most interviewers really care?

EDIT

Lets say we are inserting 1000 records.. Length will double at 4, 8, 16, 32.... So insert complexity will be Log(N) correct?

like image 887
om471987 Avatar asked Jan 21 '26 02:01

om471987


1 Answers

The complexity for that particular insert operation (where the list doubles in size) is O(N). But the amortized complexity is still O(1), because the list did not double in size for the N / 2 elements before, so the average number of operations per insertion is still constant. The interviewers probably expect you to be aware of this difference.

like image 64
meowgoesthedog Avatar answered Jan 23 '26 14:01

meowgoesthedog