VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-string-follows-anbn-pattern-not/

⇱ Check if a string follows x^n y^n pattern or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a string follows x^n y^n pattern or not

Last Updated : 26 May, 2026

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.

Check Every Valid Block Separately - O(n^2) Time O(1) Space

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.


Output
true

Time Complexity: O(n^2)
Auxiliary Space: O(1)

Single Traversal Using Counters - O(n) Time O(1) Space

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.


Output
true

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: