Program to find list of all possible combinations of letters of a given string s in Python


Suppose we have a string s. We have to find all possible combinations of letters of s. If there are two strings with same set of characters, then show the lexicographically smallest of them. And one constraint is each character in s are unique.

So, if the input is like s = "pqr", then the output will be ['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']

To solve this, we will follow these steps −

  • st_arr := a new list
  • for i in range size of s - 1 to 0, decrease by 1, do
    • for j in range 0 to size of st_arr - 1, do
      • insert (s[i] concatenate st_arr[j]) at the end of st_arr
    • insert s[i] at the end of st_arr
  • return st_arr

Example

Let us see the following implementation to get better understanding −

def solve(s):
   st_arr = []

   for i in range(len(s)-1,-1,-1):
      for j in range(len(st_arr)):
         st_arr.append(s[i]+st_arr[j])
      st_arr.append(s[i])
   return st_arr

s = "pqr"
print(solve(s))

Input

"pqr"

Output

['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']

Updated on: 25-Oct-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements