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.