Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if a string follows a^n b^n pattern or not in Python
The a^n b^n pattern refers to a string that contains exactly n consecutive 'a' characters followed by exactly n consecutive 'b' characters. For example, when n = 3, the string will be "aaabbb".
So, if the input is like s = "aaaaabbbbb", then the output will be True as this follows a^5 b^5 pattern.
Algorithm
To solve this, we will follow these steps −
- Get the size of the string
- Count consecutive 'a' characters from the beginning
- Check if the number of 'a's multiplied by 2 equals the total string length
- Verify that all remaining characters are 'b'
- Return True if both conditions are satisfied
Implementation
Let us see the following implementation to get better understanding −
def solve(s):
size = len(s)
# Count consecutive 'a' characters from start
i = 0
for i in range(size):
if s[i] != 'a':
break
# Check if number of 'a's times 2 equals total length
if i * 2 != size:
return False
# Check if remaining characters are all 'b'
for j in range(i, size):
if s[j] != 'b':
return False
return True
# Test the function
s = "aaaaabbbbb"
print(solve(s))
True
Testing Multiple Cases
Let's test the function with different examples to verify it works correctly −
def solve(s):
size = len(s)
# Count consecutive 'a' characters from start
i = 0
for i in range(size):
if s[i] != 'a':
break
# Check if number of 'a's times 2 equals total length
if i * 2 != size:
return False
# Check if remaining characters are all 'b'
for j in range(i, size):
if s[j] != 'b':
return False
return True
# Test cases
test_cases = ["aaabbb", "aabbcc", "ab", "aabb", "aaabb", ""]
for test in test_cases:
result = solve(test)
print(f"'{test}' follows a^n b^n pattern: {result}")
'aaabbb' follows a^n b^n pattern: True 'aabbcc' follows a^n b^n pattern: False 'ab' follows a^n b^n pattern: True 'aabb' follows a^n b^n pattern: True 'aaabb' follows a^n b^n pattern: False '' follows a^n b^n pattern: True
How It Works
The algorithm works by:
- Counting 'a' characters: It counts consecutive 'a' characters from the beginning of the string
- Length validation: For a valid a^n b^n pattern, the total length must be exactly 2n (n 'a's + n 'b's)
- Validating 'b' characters: It ensures all remaining characters after the 'a's are 'b' characters
Conclusion
This solution efficiently checks the a^n b^n pattern by counting consecutive 'a' characters and validating that the remaining half contains only 'b' characters. The time complexity is O(n) where n is the string length.
