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


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

Example

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"
print(solve(s))

Input

"21133123"

Output

True

Updated on: 12-Oct-2021

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements