1

An insert into a hash table has a worst case complexity of O(n).

But when creating a new hash table and inserting n elements, as far as I understand this would result in n insertions into a growing hash table. Therefore, O(1) + O(2) + O(3) + ... + O(n) = O((n^2+n)/2). So worst runtime complexity of creating a hash table with n elements would be quadratic. Is this correct?

However, average and amortized runtime complexity of inserts are O(1), therefore average and amortized runtime complexity of creating a hashmap with n elements would also be O(1)?

1 Answer 1

0

If you resize by 1 (or any other constant) on each insertion then you don't get O(1) but rather O(n) like your analysis showed.

Instead we resize by rather by some factor of the current number of elements in the hash table, the for example you double the size of the hash table whenever it gets filled (in reality we'll some load factor and don't wait until it's filled).

So for example if the number of items in your hash table is n and it was just resized then the maximum possible number of items is 2n. So now for the next resize to happen your need to perform at least n insertions and then resize is also O(n) so amortized is O(1).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.