Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the space complexity of this string manipulation code?

This piece of code is from Cracking the Coding interview book.

public static boolean isUniqueChars2(String str) {
    boolean[] char_set = new boolean[256];
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i);
        if (char_set[val]) return false;
        char_set[val] = true;
    }
    return true;
}

And the author mentions that,

Time complexity is O(n), where n is the length of the string, and space complexity is O(n).

I understand time complexity being O(n) but I don't understand how could space complexity be O(n)

My thinking: char_set will remain an array of size 256 no matter what the input (str) size is. Even if the length of "str" is 100,000, char_set is still a 256 element array. So I thought, since memory requirements for this function does not change with the size of the input and remain a constant 256, the space complexity is constant, i.e., O(1).

Can someone explain, if I am wrong (and, why?)

Thank you so much.

like image 942
anakkala Avatar asked Feb 20 '13 23:02

anakkala


People also ask

What is the space complexity of a string?

Space complexity: O(1) , Although we do use extra space for an array, the space complexity is O(1) because the array size remains constant irrespective of the length of string.

What is space complexity O 1?

a space complexity of O(1) means that the space required by the algorithm to process data is constant; it does not grow with the size of the data on which the algorithm is operating.

What is space complexity?

Space complexity refers to the total amount of memory space used by an algorithm/program, including the space of input values for execution. Calculate the space occupied by variables in an algorithm/program to determine space complexity.


1 Answers

The space complexity in that example is O(N) because the string is received as parameter; we don't know exactly it's size, and taking into account that the space complexity advices about the memory consumption in time of the algorithm, it will vary depending on the size of "str". Because of that N should be used.

Exactly the same happens if I have for example:

public void someMethod(int a[], char s, int w){...}

It will be O(N) because of "a[]" (we don't know it's size).

On the other hand:

public void someMethod(char s, int a, int x){...}

It will be O(1) (constant). Due we already know the memory allocated for the necessary attributes.

Hope it helps.

like image 83
Yamil Marques de Mello Avatar answered Sep 18 '22 20:09

Yamil Marques de Mello