-2
    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;
    }
collapsar
  • 17,010
  • 4
  • 35
  • 61
c2h5oh
  • 227
  • 5
  • 9

2 Answers2

1

Not counting the input string, the code has O(1) space complexity. It consumes a constant amount of space irrespective of the input.

The time complexity is also O(1), since the loop will never execute more than 256 steps.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    @Betlista - The function exits when the first repeated character is found or the input is exhausted. No repeated characters is the worst case. (Note, however, that by the [pigeonhole principle](http://en.wikipedia.org/wiki/Pigeonhole_principle), there can't be more than 256 unique characters.) – Ted Hopp Sep 02 '13 at 15:27
  • 4
    Technically, the loop must exit after 256 iterations, independent of the input string, so it's worst case O(1) time. –  Sep 02 '13 at 15:29
1

The size of your input is obviously O(n), but the memory requirements of this function is O(1), since the array has constant size. The time complexity is O(n) though, since it iterates over the string..

DDW
  • 1,975
  • 2
  • 13
  • 26
  • 2
    I think that the time complexity is also O(1) : There will never be more than ~26 steps, depending on the encoding and presence of special chars – Arnaud Denoyelle Sep 02 '13 at 15:27