Title is self-explanatory. Very easy question. I think it's O(n) but wanted to verify before my final tomorrow.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
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).
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).
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.
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, int
s or simple struct
s), 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With