I'm wondering if this code can be optimized in terms of time complexity. The problem is checking to see if a string has all unique characters.
#include <iostream>
#include <string>
using namespace std;
//Assuming ASCII
bool checkString (string user) {
if (user.length() > 256)
{
return false;
}
//creating a boolean array of size 256
//setting all values to false (0)
bool check[256] = {false};
for (int i = 0; i < user.length(); i++)
{
int value = user.at(i);
if (check[value] == true)
{
return false;
}
else
{
check[value] = true;
}
}
return true;
}
int main() {
string user;
cout << "Please enter in a string: ";
cin >> user;
cout << checkString(user) << endl;
return 0;
}
I'm not very good with determining the time complexity. Right now, would it be \$O(n^2)\$ (because of the for
loop)?