Program to check whether we can make k palindromes from given string characters or not in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a string s and another number k, we have to check whether we can create k palindromes using all characters in s or not.

So, if the input is like s = "amledavmel" k = 2, then the output will be True, as we can make "level" and "madam".

To solve this, we will follow these steps

  • d := a map where store each unique characters and their frequency

  • cnt := 0

  • for each key in d, do

    • if d[key] is odd, then

      • cnt := cnt + 1

    • if cnt > k, then

      • return False

  • return True

Let us see the following implementation to get better understanding

Example

from collections import Counter

class Solution:
   def solve(self, s, k):
      d = Counter(s)
         cnt = 0
         for key in d:
            if d[key] & 1:
               cnt += 1
            if cnt > k:
               return False
         return True

ob = Solution()
s = "amledavmel"
k = 2
print(ob.solve(s, k))

Input

"amledavmel",2

Output

True
raja
Published on 10-Nov-2020 14:01:27
Advertisements