# Is this algorithm of constant time?

I have the following code in Python:

def is_unique(string):
if len(string) <= 1:
return True

if len(string) > 128:
return False

char_set = defaultdict(lambda: False)

for char in string:
if not char_set[char]:
char_set[char] = True
else:
return False

return True


It's basically checking if a string is unique or not. I think that my algorithm is O(1):

No matter what it's the length of the string, I will only iterate over at most 128 times in the worst case. All the operations (len, dict lookup etc) are of constant time as well.

I guess my generic question here is if you can proof that your algorithm will always iterate for a constant number of times, can you claim that this is O(1)?

• We normally ask for code to be replaced by pseudocode, to make questions accessible to people who don't know the language that's being used. In this case, I suppose the Python is OK, since you've stated enough assumptions to answer the question without needing to understand the details of the code. – David Richerby Nov 30 '18 at 0:03

Generally yes. I mean if an algorithm can run in $$O(f(n)) = c$$ time, where $$c$$ is a $$constant$$, then it is in $$O(1)$$ time.