Program to find number of string we can make where 'a' can be 'a' or 'b', and 'b' remains 'b'in Python

Suppose we have a string s with only "a" and "b". "a"s can stay "a" or turn into "b", but "b"s can not be changed. We have to find the number of unique strings that we can make.

So, if the input is like s = "baab", then the output will be 4, as we can make these strings ? ["baab", "babb", "bbab", "bbbb"]

Approach

The key insight is that only characters 'a' can be transformed. Each 'a' has 2 choices (remain 'a' or become 'b'), while 'b' characters remain unchanged. If we have n occurrences of 'a', the total combinations will be 2^n.

To solve this, we will follow these steps ?

  • counts := frequency of 'a' in s
  • return 2^counts

Example

class Solution:
    def solve(self, s):
        counts = s.count('a')
        total = 2**(counts)
        return total

ob = Solution()
print(ob.solve("baab"))
4

How It Works

For the string "baab":

  • Position 1: 'b' (fixed) ? 'b'
  • Position 2: 'a' (choice) ? 'a' or 'b'
  • Position 3: 'a' (choice) ? 'a' or 'b'
  • Position 4: 'b' (fixed) ? 'b'

With 2 'a's having 2 choices each: 2^2 = 4 unique strings.

Alternative Implementation

def count_unique_strings(s):
    """Count unique strings where 'a' can become 'a' or 'b'"""
    a_count = s.count('a')
    return 2 ** a_count

# Test with different examples
test_cases = ["baab", "aaa", "bbb", "ab", "ba"]

for test in test_cases:
    result = count_unique_strings(test)
    print(f"String: '{test}' ? Unique strings: {result}")
String: 'baab' ? Unique strings: 4
String: 'aaa' ? Unique strings: 8
String: 'bbb' ? Unique strings: 1
String: 'ab' ? Unique strings: 2
String: 'ba' ? Unique strings: 2

Conclusion

The solution counts occurrences of 'a' and calculates 2^count, since each 'a' can independently choose between staying 'a' or becoming 'b'. This gives us the total number of unique string transformations possible.

---
Updated on: 2026-03-25T10:38:13+05:30

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements