Program to check we can get a digit pair and any number of digit triplets or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a numeric string s. We have to check whether there is some arrangement where we can have one pair of the same character and the rest of the string form any number of triplets of the same characters.

So, if the input is like s = "21133123", then the output will be True, because there are two 2s to form "22" as the pair and "111", "333" as two triplets.

To solve this, we will follow these steps −

  • d := a list containing frequencies of each elements present in s

  • for each k in d, do

    • d[k] := d[k] - 2

    • if d[i] mod 3 is 0 for all i in d, then

      • return True

    • d[k] := d[k] + 2

  • return False


Let us see the following implementation to get better understanding

from collections import Counter
def solve(s):
   d = Counter(s)
   for k in d:
      d[k] -= 2
      if all(d[i] % 3 == 0 for i in d):
         return True
      d[k] += 2
   return False

s = "21133123"




Published on 12-Oct-2021 11:28:59