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.

Algorithm

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))

The output of the above code is ?

True

How It Works

The algorithm tries each character as a potential pair candidate. For each character, it temporarily removes 2 occurrences (forming a pair) and checks if all remaining characters can form triplets (divisible by 3). If this works for any character, we return True.

Step-by-Step Breakdown

from collections import Counter

def solve_detailed(s):
    d = Counter(s)
    print(f"Character frequencies: {d}")
    
    for k in d:
        print(f"\nTrying to use '{k}' as pair:")
        d[k] -= 2
        print(f"After removing pair of '{k}': {d}")
        
        # Check if all remaining can form triplets
        if all(d[i] % 3 == 0 for i in d):
            print("All remaining characters can form triplets!")
            return True
        
        d[k] += 2  # Restore the count
        print(f"Restored: {d}")
    
    return False

s = "21133123"
result = solve_detailed(s)
print(f"\nFinal result: {result}")
Character frequencies: Counter({'1': 3, '3': 3, '2': 2})

Trying to use '1' as pair:
After removing pair of '1': Counter({'3': 3, '1': 1, '2': 2})
Restored: Counter({'1': 3, '3': 3, '2': 2})

Trying to use '3' as pair:
After removing pair of '3': Counter({'1': 3, '3': 1, '2': 2})
Restored: Counter({'1': 3, '3': 3, '2': 2})

Trying to use '2' as pair:
After removing pair of '2': Counter({'1': 3, '3': 3, '2': 0})
All remaining characters can form triplets!

Final result: True

Conclusion

This solution efficiently checks if a string can be arranged into one pair and multiple triplets by testing each character as a potential pair candidate. The time complexity is O(n) where n is the number of unique characters.

Updated on: 2026-03-26T15:53:29+05:30

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements