Letter Tile Possibilities in Python

PythonServer Side ProgrammingProgramming

Suppose we have a set of tiles, where each tile has one letter tiles[i] printed on it. Find the number of possible non-empty sequences of letters that we can make. So if the input is “AAB”, then the output will be 8. As sequences are “A”, “B”, “AA”, “AB”, “BA”, “AAB”, “ABA”, “BAA”

To solve this, we will follow these steps −

  • Define one dfs(), that will take count
  • sum := 0
  • for i in range 1 to 26
    • if count[i] = 0, then go for next iteration, without checking the rest
    • decrease count[i] by 1, and increase sum by 1
    • sum := sum + dfs(count)
    • increase count[i] by 1
  • return sum
  • the actual method will be like −
  • make one count array of size 26, and fill this with 0
  • for each element i in tiles
    • increase count[i – ‘A’ + 1] by 1
  • return dfs(count)

Let us see the following implementation to get better understanding −


 Live Demo

class Solution(object):
   def numTilePossibilities(self, tiles):
      count = [0 for i in range(27)]
      for i in tiles:
      return self.dfs(count)
   def dfs(self,count):
      summ = 0
      for i in range(1,27):
         if count[i]==0:
      return summ
ob = Solution()




Published on 30-Apr-2020 12:21:47