1

In the book "Cracking the Coding Interview", first exercise says "Implement an algorithm to determine if a string has all unique characters (not using additional data structures)". And the solution:

public static boolean isUniqueChars(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;
}

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

I don't see why space complexity is O(n). The array char_set has a constant length, independent on how long the given str is. To me, space complexity is O(1).

5
  • 3
    I agree, it's constant. Unless you're considering the char array that backs String as included (I wouldn't, that's part of the input, not the algorithm)
    – Michael
    Jul 5, 2020 at 15:45
  • I think str - O(n) and cha_set - O(1) then it's O(n), input also part of space complexity
    – Eklavya
    Jul 5, 2020 at 15:50
  • Are you sure this is Java code?? Because then the solution is wrong. It assumes that charAt(i) returns an unsigned byte, but it really returns a char(2 bytes) , so char_set should be[256*256]. This also shows why the time use is really O(1) because, the max number of iterations is 256*256.
    – MTilsted
    Jul 5, 2020 at 15:55
  • Looks O(1) to me...
    – MC Emperor
    Jul 5, 2020 at 16:12
  • @Eklavya The input is not part of the space complexity of the method.
    – Andreas
    Jul 5, 2020 at 16:15

1 Answer 1

2

Its space complexity is O(1) (\Theta(1)) as it keeps 256 (constant) bits more than the size of the input array. Also, the time complexity is O(1) as there are 256 chars to be checked in the input string and the duplicate will be detected at most at 256th character of the string.

2
  • 2
    But it will never scan more than 256 characters, no matter how long the input string is. Jul 5, 2020 at 16:05
  • @MikeHarris The tighter bound is O(1). However, O(n) was correct. Thanks. It's updated.
    – OmG
    Jul 5, 2020 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.