patternMinor
Determine if a string has all unique characters
Viewed 0 times
uniqueallhasdeterminecharactersstring
Problem
I'm practicing algorithms (for future interviews) while learning about Big O notation and was wondering if there's a faster or more optimal way of writing an algorithm to see if a string has all unique characters (assuming you can't use additional data structures).
If I'm correct, is the time complexity for this \$O(n^2)\$, and the space complexity \$O(1)\$?
- (BOOL)containsUniqueCharacters:(NSString *)string {
//Make sure that it's case insensitve
string = [string uppercaseString];
//Create a buffer for our string
NSUInteger length = [string length];
unichar buffer[length];
[string getCharacters:buffer range:NSMakeRange(0, length)];
//Iterate through each of our characters
for (int i = 0; i < length; i++) {
//Iterate through every other character and compare it with our current character
for (int n = 0; n < length; n++) {
//Compare current character with every other character
if (buffer[i] == buffer[n] && i != n) {
return NO;
}
}
}
return YES;
}If I'm correct, is the time complexity for this \$O(n^2)\$, and the space complexity \$O(1)\$?
Solution
I would suggest an algorithmically better O(n) solution by using a buffer or hashtable or other such structure to record whether or not you have "seen" a character.
For example if you are dealing with a basic string containing char, then you can get away with a bitset of size 256. Each character you see marks a bit. If the bit was already marked, return
Furthermore, if the size of the string you're testing is longer than 256, then that is an automatic
Since you are dealing with unicode for which the possible values a character can take are very many, then you will want to use a hash table. It will be dramatically faster than even any O(n log n) sorting method.
For example if you are dealing with a basic string containing char, then you can get away with a bitset of size 256. Each character you see marks a bit. If the bit was already marked, return
YES.Furthermore, if the size of the string you're testing is longer than 256, then that is an automatic
NO (not all unique chars) as well.Since you are dealing with unicode for which the possible values a character can take are very many, then you will want to use a hash table. It will be dramatically faster than even any O(n log n) sorting method.
Context
StackExchange Code Review Q#63625, answer score: 6
Revisions (0)
No revisions yet.