![]() |
VOOZH | about |
Given a string s made of two characters of 'x' and 'y'. you need to verify whether the string is made by concatenating substrings that follow the pattern xnyn (equal number of y's follow equal number of x's). As an example: "xxyyxxyy" is valid. "xy" is valid. "xxyyx" is invalid. "xxxyyyxxyyxy" is valid.
Examples:
Input: s = "xxyyxy"
Output: true
Explanation: The string can be divided into valid blocks where equal consecutive 'x' are followed by equal consecutive 'y'.
Input: s = "xyx"
Output: false
Explanation: The count of 'x' and 'y' is not equal.
Table of Content
The idea is to build substrings continuously while traversing the string. For every formed substring, check whether it follows the pattern xⁿ yⁿ, i.e., equal number of consecutive 'x' followed by equal number of consecutive 'y'. Whenever a valid substring is found, start forming a new substring. If the entire string gets divided into valid parts, return true; otherwise return false.
true
Time Complexity: O(n^2)
Auxiliary Space: O(1)
The idea is to traverse the string once and count consecutive 'x' and 'y' characters for every block. First count all consecutive 'x', then count consecutive 'y'. If both counts become equal, reset the counters and continue checking the next block. If at any point the counts differ, the string is invalid. If all blocks satisfy the pattern xⁿ yⁿ, return true.
true
Time Complexity: O(n)
Auxiliary Space: O(1)