2

What's the time complexity of the following code in C++: (note that I'm using gcc, so len is taken as an input from the user)

int array[len]; \\array is uninitialized

Is it O(1) or O(len) ? I am a bit confused.

katana_0
  • 183
  • 1
  • 8

2 Answers2

5

In general for POD types the time will be O(1).

If you have user defined constructors (or destructors, I assume that the time taken to release the resources should also be considered) then I would expect the time complexity to be O(n).

If you can wait a little, I submitted an article to Overload on the code size and execution time required for objects that are allocated automatically and dynamically. I'm expecting it to be out this April.

Update: Here is the link for the published Overload article No news is good news

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
1

The general rule:

type name[size];

If your type is Plain Old Data (POD) than compiler can invoke allocation and construction in O(1).
Otherwise en explicit constructor call is required for each entity which is O(n).

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76