Search code examples
data-structuresinitializationtime-complexityinit

How to know if init operation of empty data structure costs us O(1) or more? (on general)


I didn't find resources about how to choose the time complexity of init of empty data structure. I know it is based on implementation and programing languages, but I assume there are conventions. For example, it is known that init of hash table is O(1), but it looks that init empty array (not dyanamic) is O(n).

I thought that I can handle it thorough a based array implementations (which is most effiecent by space and ADT operaitons) such as BST, AVL, Heap (which can be shown in O(n)), and non array based implementations like linked list, stack and so on (O(1)).It sounds not that accurate because if we want to init empty 2D array the time complexity is O(n^2), which sound expensive. Other example is also that we can init empty array with hash table which is O(1). I would like to have a Clarifications about it.


Solution

  • I don't know what the formal conventions are, but allocation is typically O(1) in practice. The OS can cheat by promising memory to a process, but not actually assigning hardware resources until the process writes to part of that memory. So in that sense, allocating 1 byte or 1 GB are generally similar (however, there are always exceptions).

    Similarly, the actual initialization depends what you mean by empty. If empty means uninitialized, then the process does not need to spend any extra time creating the structure. However, if you have some sort of initialized state you want to set the memory to, then it would be O(n) based on how many elements you initialize. Keep in mind though that this time is often close to negligible in most applications compared to other factors like cache hit rate.

    Instead, I would suggest breaking up the time-complexity and memory-complexity so they can be displayed separately. In this case, the time-complexity does not include allocation/initialization time and only includes the actual algorithm. The memory-complexity is similar to time-complexity, but represents an approximation of the total memory required as n changes.