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.

14
  • 1
    To clarify, you are asking about the VLA extension that GCC provides? Commented Mar 8, 2018 at 12:15
  • 3
    This might be better posed as new int[len]. I'm pretty certain that automatic variable allocation will be O(1), dynamic might have a O(log(len)) feel to it if the OS needs to start thinking harder about paging &c. Commented Mar 8, 2018 at 12:16
  • 1
    I'm fairly sure if you look at the asm; it'll be O(1) ... if you have some more interesting objects though i'll be O(N) Commented Mar 8, 2018 at 12:18
  • 1
    What is len defined as? Commented Mar 8, 2018 at 12:19
  • 1
    @AlexKChen who knows - like I said; depends on Foo and what the compiler can optimise away. Commented Mar 8, 2018 at 12:22

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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).

1 Comment

The OP is asking about VLA extension of GCC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.