views:

297

answers:

3

I want to know the space complexities of the basic data structures in popular languages.

+1  A: 

Virtually all data structures with a non-trivial size are on the ORDER of n.

  • Array = exactly n
  • ArrayList = betweenn and k*n (default k=2)
  • LinkedList = exactly n
  • HashTable = worst is n/k (default k is .75)
glowcoder
Linked list is exactly n, 'ay? Hash table requires less n space to store n elements? :)
BlueRaja - Danny Pflughoeft
LinkedList is exactly n. Look at the source of it. It consists of a header entry and an int for the size. Perhaps I should have mentioned the int size? And if you do the math on my HashTable, you'll see n/k, not n*k. - for example, if you have n of 1000, and k of .75, 1000/.75 = 1334, which is clearly more than 1000.
glowcoder
If there's a criticism to be had here, it's that ArrayList and HashTable don't shrink when you remove, so n should be interpreted as the greatest n to date for those.
glowcoder
+3  A: 

All of these have space complexity O(n). All that changes is the coefficient, and that is completely dependent on the implementation. Especially when you start getting into things like pre-allocating space to reduce time complexity.

For instance, array list structures generally pre-allocate extra space. Therefore, their exact complexity for a number of objects is actually a range which is completely dependent on implementation and how they were created and used. For instance, if I write an array list that always allocates three extra spaces whenever more space is necessary, and always deallocates down to three open spaces when there's more than 5 open spaces, then actual complexity for n will be [n, n + 5] + overhead.

The big differences in choosing between these items when programming is usually ease-of-use and how well it fits with how you will be using it. For example, linked lists are horrible for random access, but great at iteration.

jdmichal
+1  A: 

For Java: (Aproximates)

            Memory O(x) | General Case
Array     |       n     |    n
ArrayList |       n     |    2 * n
LinkedList|       n     |    n * (node size)
HashTable |       n     |    ~n
Map       |       n     |    (n * key_size) + n
jjnguy
What the heck does 'general' mean?
bdonlan
@bdonlan It is my best guess for the memory use of a general implementation of the structure.
jjnguy
That doesn't really make much sense. For array, does n mean n bytes? If it means n items, then linkedlist is n * node size * item size bytes...?
bdonlan
@bdonlan I think of it as n = number of items * their size. So, an array will take up n elements. This isn't supposed to be an official doc...
jjnguy
My point is, the math is just wrong in places. LinkedList = `number of items * item size * node size` has dimensionality `byte^2`. You're not being consistent with what n means, and so the equations you give are meaningless...
bdonlan