- Related Questions & Answers
- GROUP BY the number of rows returned by GROUP BY in MySQL?
- How I can check if A is superclass of B in Python?
- How to determine if a value appears in a GROUP BY group in MySQL?
- Getting a list of values by using MongoDB $group?
- Check if N is divisible by a number which is composed of the digits from the set {A, B} in Python
- Get average of every group of n elements in an array JavaScript
- Check if it is possible to reach a number by making jumps of two given length in Python
- Python Group elements at same indices in a multi-list
- Python Group by matching second tuple value in list of tuples
- Check if matrix A can be converted to B by changing parity of corner elements of any submatrix in Python
- Check if the frequency of all the digits in a number is same in Python
- Check if mirror image of a number is same if displayed in seven segment displays in Python
- Check if a string is entirely made of the same substring JavaScript
- Check if leaf traversal of two Binary Trees is same in Python
- Check if a string contains a palindromic sub-string of even length in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a lowercase string s with only two characters a and b. We have to check whether every group of consecutive a's is followed by group of consecutive b's of equal length.

So, if the input is like s = "abaaabbbaabbaabbab", then the output will be True, as all groups are (ab), (aaabbb), (aabb), (aabb), (ab).

To solve this, we will follow these steps −

- a_count := 0, string_len := size of s
- i := 0
- while i < string_len, do
- while i < string_len and s[i] is 'a', do
- a_count := a_count + 1
- i := i + 1

- while i < string_len and s[i] is 'b', do
- a_count := a_count - 1
- i := i + 1

- if a_count is not 0, then
- return False

- while i < string_len and s[i] is 'a', do
- return True

Let us see the following implementation to get better understanding −

def solve(s): a_count = 0 string_len = len(s) i = 0 while i < string_len: while i < string_len and s[i] == 'a': a_count += 1 i += 1 while i < string_len and s[i] == 'b': a_count -= 1 i += 1 if a_count != 0: return False return True s = "abaaabbbaabbaabbab" print(solve(s))

"abaaabbbaabbaabbab"

True

Advertisements