The space complexity of the code snippet given below-
int *a=malloc(n*sizeof(int)); int sum=0; for(i=0;i<n;i++) { scanf("%d",&a[i]); for(j=0;j<n;j++) { int x=a[i]; sum=sum+x; } } free(a);
This is question of a test. I answered it O(n), considering space only for array and constant space for rest of the code. But in the answer they given O(n^2) and there explanation is "The array is of size n and the inner most loop we are declaring a variable x every time the loop is executed, this loop is executed O(n^2) time hence overall space complexity is O(n^2)." Now my doubt is what should be space complexity of
for(i=1;i<=n;i++) int x=10;
What i thought is that it should be O(1) because in each iteration variable x gets destroyed. Please someone help me…i searched but found nothing satisfactory.