-1

I have a piece of code of which space complexity is to be calculated in Big-O notation

 int a = 0, b = 0;    
    for (i = 0; i < N; i++) {
        a = a + rand();  
    }
    for (j = 0; j < M; j++) {
        b = b + rand();
    }

The rand() is an O(1) space.

I think the answer should be O(max(M,N)) but the answer in my textbook is O(1). Shouldn't the space depend on N and M?

natzelo
  • 66
  • 7
  • 1
    N, M are constants. They don't change. Also you seem to confuse space with time. There is no extra space here used. Space is used when you allocate some memory to store intermediate results etc. – SomeDude Apr 14 '20 at 14:15
  • 1
    `a` and `b` are both of type Int32. Their size is independent of N and M. Thus space complexity is O(1). – Jacek Apr 14 '20 at 14:17
  • 1
    The only space taken are by variables a, b, M, N which is constant and hence O(1). The runtime is dependent on the values of M and N. – Subhodeep Maji Apr 14 '20 at 14:18

1 Answers1

2

Space complexity here does not depend on N and M. Space complexity depends on int so the Space Complexity is O(1).
Time Complexity is O(max(M,N)) and O(n) is just enough, no need for too much details (i mean here on max(M,N))

Strahinja
  • 440
  • 9
  • 26
  • 1
    fwiw, even including the details it is `O(N)`. For any fixed `M` and `N` you can find a constant `k` such that `M == k*N`, then `O( max(M,N)) == O( max(k*N,N)) == O(N)` – 463035818_is_not_an_ai Apr 14 '20 at 15:18