Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Big-O of the C++ statement 'delete [] Q;' O(1) or O(n)?

Title is self-explanatory. Very easy question. I think it's O(n) but wanted to verify before my final tomorrow.

like image 352
Ethan Barron Avatar asked May 09 '13 21:05

Ethan Barron


People also ask

How delete [] is different from delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.

What is the time complexity of delete?

In general, time complexity is O(h). Deletion: For deletion of element 1, we have to traverse all elements to find 1 (in order 3, 2, 1). Therefore, deletion in binary tree has worst case complexity of O(n). In general, time complexity is O(h).

Which of the below is the correct Big O expression for 1 2 3 N?

The answer is O(1) if you use the formula for summation directly. Save this answer. Show activity on this post. the addition is called n times, so the whole code has a time complexity of O(1) * n = O(n).

What is O N and O n2?

O(n) is always O(n^2). Big-Theta (Θ) would be what you're looking for if you want a tight (lower >= and upper <=) bound.


1 Answers

The short answer is... it depends.

If Q is a pointer to an array of objects that have destructors, then delete[] Q will need to call all of those destructors. This will call O(n) destructors, where n is the number of elements in the array. On the other hand, if Q points to an array of objects that don't have destructors (for example, ints or simple structs), then no destructors need to be called, which takes only O(1) time.

Now note that those destructors don't have to run in O(1) time each. If the objects are, say, std::vector objects, then each destructor in turn has to fire off more deallocations. Without knowing more about what those objects are, all we can say is that if there are destructors called, there will be 0 destructors called if the destructors are trivial and O(n) destructors called otherwise.

But this ignores the implementation detail of how the heap allocator works. It's possible that deallocating a block of memory might take O(log K) time, where K is the total number of allocated blocks, or it might take O(1) time regardless of how many blocks of memory there are, or it might take O(log log K), etc. Without knowing how the allocator works, you honestly can't be sure.

In short, if you focus purely on the work required to clean up the objects before handing the block back to the memory allocator, there are O(n) destructors called if the objects stored have destructors and 0 destructors called otherwise. These destructors might take a nontrivial amount of time to complete. Then, there's the cost of reintroducing the block of memory back into the memory allocator, which might take its own amount of time.

Hope this helps!

like image 185
templatetypedef Avatar answered Nov 15 '22 20:11

templatetypedef