In this article, we will learn about the solution and approach to solve the given problem statement.
Given a sring input, we need to find whether a string contains all unique characters or not.
We will create an array of boolean values, where the variable flag at the index i indicates that whether character i in the alphabet is contained in the string or not.
The second time we encounter this character we can immediately return false as string characters is no longer unique.
We can also return false if the string length exceeds the value of number of unique characters presnt in the alphabet.
Herw we have fixed the size of string to 256 maximum
Now let’s see the implementation −
def isUniqueChars(st): if len(st) > 256: return False # Initialization char_set = [False] * 128 # in char_set for i in range(0, len(st)): # ASCII value val = ord(st[i]) if char_set[val]: return False char_set[val] = True return True # main st = "tutorialspoint" print(isUniqueChars(st))
All the variables are declared in the global frame as shown in the figure given below −
In this article, we learned about the approach to check if a string contains all unique characters