Program to find number of ways we can concatenate words to make palindromes in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of distinct words, we have to find the number of different ways we can concatenate two different words from the given list of words to make a palindrome.

So, if the input is like words = ["time", "emit", "mo", "m"], then the output will be 3, as we can make "timeemit", "emittime", and "mom".

To solve this, we will follow these steps −

  • res := 0

  • ln := number of words in the array

  • for k in range 0 to 1, do

    • for i in range 0 to ln − 1, do

      • for j in range i + 1 to ln − 1, do

        • res := res + (1 when words[i] concatenate words[j] is palindrome, otherwise 0)

    • words := words in reverse order

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, words):
      def is_palindrome(w1, w2):
         w3 = w1 + w2
         return w3 == w3[::−1]
      res = 0
      ln = len(words)
      for k in range(2):
         for i in range(ln):
            for j in range(i + 1, ln):
               res += is_palindrome(words[i], words[j])
            words = words[::−1]
      return res
ob = Solution()
words = ["time", "emit", "mo", "m"]
print(ob.solve(words))

Input

["time", "emit", "mo", "m"]

Output

3
raja
Published on 15-Dec-2020 12:46:26
Advertisements