The following code attempts to find out if a given string has unique characters or not. I have solved it through creating a hash table: A list of lists. I am thinking the time complexity is as follows: Someone please tell me if I am going about it the right way:
The first for loop loops through every character in a string, let the size of a string be denoted as 's'
The second for loop goes through every element in the list within the list: This would be of smaller size than s. Let n be the number of elements in the hash table: In the worst case scenario: it can be n/s = 1. Otherwise avg case scenario it can be n/s < 1
So, the time complexity worst case: O(s^2) otherwise O(s*n/s) = O(n)
def IsItUnique(String):
size = len(String)
hashtable = [[] for i in range(size)]
for every_char in String:
hash_code = (ord(every_char) - ord('a')) % size
if(hashtable[hash_code] is None):
hashtable[hash_code].append(every_char)
else:
for every_element in hashtable[hash_code]:
if every_element == every_char:
return False
hashtable[hash_code].append(every_char)
return True
def main():
String = "abcdefgja"
String2 = "apples"
String3 = "azmdskfj;"
isit1 = IsItUnique(String)
isit2 = IsItUnique(String2)
isit3 = IsItUnique(String3)
print(isit1, isit2, isit3)
if __name__=="__main__":
main()