Is Unique

1.1 Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

#include <iostream>

using namespace std;

// ASCII assumed over unicode
// Not good enough -> O(n^2)
// Depending on size of string of course-> better with smaller strings
bool isUnique(string s) {
    for (int i = 0; i < s.size(); i++) {
        for (int j = 0; j < s.size(); j++) {
            if (i == j) continue;
            if (s.at(i) == s.at(j)) return false;
        }
    }
    return true;
}

int main()
{
    cout << boolalpha << isUnique("Foo") << endl;
    cout << boolalpha << isUnique("Daniel") << endl;
    cout << boolalpha << isUnique("damnsonlol") << endl;
}
#include <iostream>

using namespace std;

// ASCII assumed over unicode
// O(n) algorithm
// O(1) space
bool isUnique(string s) {
    // cannot exceed number of unique characters
    if (s.length() > 256) return false;
    bool checker[256];
    for (int i = 0; i < s.length(); i++) {
        int val = s.at(i);
        if (checker[val] == true)
            return false;
        checker[val] = true;
    }
    return true;
}

int main()
{
    cout << boolalpha << isUnique("Foo") << endl;
    cout << boolalpha << isUnique("Daniel") << endl;
    cout << boolalpha << isUnique("damnsonlol") << endl;
}

Last updated