0
#include <iostream>
using namespace std;
int main()
{
    int a[100][100]={10};
    cout<<a[0][0];
    return 0;
}

what is the time complexity of above program? is it O(1) or O(100^2)??

4
  • Initializing an array that way is done by the compiler at time of compilation, so it's O(1) during run-time. Commented Feb 6, 2015 at 7:47
  • 1
    The above code does not set all element to 10. Only a[0][0] will be 10 Commented Feb 6, 2015 at 7:49
  • 8
    O(100^2) is the same as O(1). Commented Feb 6, 2015 at 7:49
  • To clarify: there is nothing in your code that can change. There's no N in it. It will always run the same thing. So, O(1). Commented Feb 6, 2015 at 7:56

3 Answers 3

4
  • Initializing an array is O(N).
  • O(k) == O(1) (for constant k, k > 0).

As your array have fixed size, the complexity of the program is O(1).

if you change your program to something like:

#include <iostream>
#include <vector>
int main()
{
    int size;
    std::cin >> size;
    std::vector<int> a(size);
    // ..
}

There, the initialization of a is O(N).

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

Comments

1

All values in your code are constant, so its execution time is constant: O(1).

(Of course the actual time depends on the machine you choose to run the program as well as on unpredictable external conditions, like the overall system load at the execution time.)

Comments

0

Time complexity is constant because consider allocating space with malloc(sizeof(int)*rows*cols) where rows and cols have been defined before.

Also, the array indexing happens in constant time. Therefore, overall it is constant.

Comments

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.