Python program to check if a string contains all unique characters

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution and approach to solve the given problem statement.

Problem statement

Given a sring input, we need to find whether a string contains all unique characters or not.

Approach

  • 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 −

Example

 Live Demo

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))

Output

False

All the variables are declared in the global frame as shown in the figure given below −

Conclusion

In this article, we learned about the approach to check if a string contains all unique characters

raja
Published on 26-Sep-2019 15:44:14
Advertisements