tags:

views:

48

answers:

3

Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

+1  A: 
for each character in the string
  if any subsequent character matches it
    fail
succeed
WhirlWind
i think we need to sort the string for that which is not a very efficient solution
Jonathan
Why would you need to sort it for that?
WhirlWind
oh u meant compare each character with the all the others characters of the string but that would result in a O(n*n) complexity
Jonathan
Yes, the complexity is high, but I can't think of a more efficient way to do it with no data structures, and a negative vote doesn't help my brain. If you wanted a more efficient algorithm, it would have been nice to have asked in your question.
WhirlWind
This would work well as a recursive algorithm. Bonus: some people may not consider using the stack as an "additional data structure," although I think they'd be wrong. :)
Parappa
A: 

One possible solution - You could extract the string into an array of characters, sort the array, and then loop over it, checking to see if the next character is equal to the current one.

Justin Ethier
+1  A: 

If you can use a little auxiliary memory, then a small array of bits (indexed by the numerical code of the character) is all you need (if your characters are 4-byte Unicode ones you'll probably want a hashmap instead;-). Start with all bits at 0: scan the string from the start -- each time, you've found a duplicate if the bit corresponding to the current character is already 1 -- otherwise, no duplicates yet, set that bit to 1. This is O(N).

If you can't allocate any extra memory, but can alter the string, sorting the string then doing a pass to check for adjacent duplicates is the best you can do, O(N log N).

If you can't allocate extra memory and cannot alter the string, you need an O(N squared) check where each character is checked vs all the following ones.

Alex Martelli