Sunday, July 8, 2012

String with unique characters


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

Idea 1(Brute-force-O(n^2) No Extra Memory)
bool unique1(char str[]){
    for(int i = 0; str[i]; i++){
        for(int j = i+1; str[j]; j++){
            if(str[i] == str[j])
                return false;
        }
    }
    return true;
}
Idea 2(O(nlogn)-No Extra Memory)
We can sort the string using a O(nlogn) sorting algorithm then just a linear scan O(n) to find out duplication.
bool unique2(string s){
    sort(s.begin(), s.end());
    string::iterator it;
    for( it = s.begin() + 1; it != s.end(); it++){
        if(*it == *(it-1))
           return false;
    }
    return true;
}
Idea 3 (O(n)- Extra Memory O(charset))
bool unique3(char s[]){
    bool used[256];
    memset(used,false,sizeof(used));
    for( int i = 0; s[i]; i++){
        if(used[s[i]]){
            return false;
        }
        used[s[i]] = true;
    }
    return true;
}
Idea 4 (O(n)- Extra Memory one 32 bit int)
If all the char are in this range ('a' to 'z') or ('A' to 'Z') then we can easily use an int for tracking duplicate. To set a bit we can use,
bitmask |= 1 << posBit;
To check a bit we can use,
(bitmask & 1 << posBit)
See code to get the idea.
bool unique4(char s[]){
    int bitmask = 0,tmp;
    for( int i = 0; s[i]; i++){
        tmp = 1 << (s[i] - 'a');
        if(bitmask & tmp)return false;
        bitmask |= tmp;
    }
    return true;
}

No comments:

Post a Comment