Check if a string follows x^n y^n pattern or not (original) (raw)
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 x n y n (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
- Check Every Valid Block Separately - O(n^2) Time O(1) Space
- Single Traversal Using Counters - O(n) Time O(1) Space
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.
C++ `
#include using namespace std;
// Function to check whether a substring // follows the pattern x^n y^n bool isValid(string &p) { int n = p.length();
int xCount = 0;
int yCount = 0;
int i = 0;
// Count consecutive x's
while (i < n && p[i] == 'x')
{
xCount++;
i++;
}
// Count consecutive y's
while (i < n && p[i] == 'y')
{
yCount++;
i++;
}
// Valid only if:
// 1. Entire string is processed
// 2. Count of x and y is same
// 3. At least one x exists
return (i == n && xCount == yCount && xCount > 0);}
bool findPattern(string &s) { int n = s.length();
string curr = "";
// Build substrings one by one
for (int i = 0; i < n; i++)
{
curr += s[i];
// If current substring is valid,
// start forming next substring
if (isValid(curr))
{
curr = "";
}
}
// If no leftover substring remains,
// the pattern is valid
return curr.empty();}
// Driver Code int main() {
string s1 = "xxyyxy";
cout << (findPattern(s1) ? "true" : "false") << endl;
return 0;}
Java
import java.util.*;
// Function to check whether a substring // follows the pattern x^n y^n class GfG {
public static boolean isValid(String p)
{
int n = p.length();
int xCount = 0;
int yCount = 0;
int i = 0;
// Count consecutive x's
while (i < n && p.charAt(i) == 'x') {
xCount++;
i++;
}
// Count consecutive y's
while (i < n && p.charAt(i) == 'y') {
yCount++;
i++;
}
// Valid only if:
// 1. Entire string is processed
// 2. Count of x and y is same
// 3. At least one x exists
return (i == n && xCount == yCount && xCount > 0);
}
public static boolean findPattern(String s)
{
int n = s.length();
String curr = "";
// Build substrings one by one
for (int i = 0; i < n; i++) {
curr += s.charAt(i);
// If current substring is valid,
// start forming next substring
if (isValid(curr)) {
curr = "";
}
}
// If no leftover substring remains,
// the pattern is valid
return curr.isEmpty();
}
// Driver Code
public static void main(String[] args)
{
String s1 = "xxyyxy";
System.out.println(findPattern(s1) ? "true"
: "false");
}}
Python
""" Function to check whether a substring follows the pattern x^n y^n """
def is_valid(p): n = len(p)
x_count = 0
y_count = 0
i = 0
# Count consecutive x's
while i < n and p[i] == 'x':
x_count += 1
i += 1
# Count consecutive y's
while i < n and p[i] == 'y':
y_count += 1
i += 1
# Valid only if:
# 1. Entire string is processed
# 2. Count of x and y is same
# 3. At least one x exists
return i == n and x_count == y_count and x_count > 0def find_pattern(s): n = len(s)
curr = ''
# Build substrings one by one
for i in range(n):
curr += s[i]
# If current substring is valid,
# start forming next substring
if is_valid(curr):
curr = ''
# If no leftover substring remains,
# the pattern is valid
return not currDriver Code
if name == 'main': s1 = 'xxyyxy'
print('true' if find_pattern(s1) else 'false')C#
using System;
// Function to check whether a substring // follows the pattern x^n y^n public class GfG { public static bool IsValid(string p) { int n = p.Length;
int xCount = 0;
int yCount = 0;
int i = 0;
// Count consecutive x's
while (i < n && p[i] == 'x') {
xCount++;
i++;
}
// Count consecutive y's
while (i < n && p[i] == 'y') {
yCount++;
i++;
}
// Valid only if:
// 1. Entire string is processed
// 2. Count of x and y is same
// 3. At least one x exists
return (i == n && xCount == yCount && xCount > 0);
}
public static bool FindPattern(string s) {
int n = s.Length;
string curr = "";
// Build substrings one by one
for (int i = 0; i < n; i++) {
curr += s[i];
// If current substring is valid,
// start forming next substring
if (IsValid(curr)) {
curr = "";
}
}
// If no leftover substring remains,
// the pattern is valid
return curr.Length == 0;
}
// Driver Code
public static void Main() {
string s1 = "xxyyxy";
Console.WriteLine(FindPattern(s1)? "true" : "false");
}}
JavaScript
"use strict";
// Function to check whether a substring // follows the pattern x^n y^n function isValid(p) { let n = p.length;
let xCount = 0;
let yCount = 0;
let i = 0;
// Count consecutive x's
while (i < n && p[i] === 'x') {
xCount++;
i++;
}
// Count consecutive y's
while (i < n && p[i] === 'y') {
yCount++;
i++;
}
// Valid only if:
// 1. Entire string is processed
// 2. Count of x and y is same
// 3. At least one x exists
return (i === n && xCount === yCount && xCount > 0);}
function findPattern(s) { let n = s.length;
let curr = "";
// Build substrings one by one
for (let i = 0; i < n; i++) {
curr += s[i];
// If current substring is valid,
// start forming next substring
if (isValid(curr)) {
curr = "";
}
}
// If no leftover substring remains,
// the pattern is valid
return curr.length === 0;}
// Driver Code const s1 = 'xxyyxy';
console.log(findPattern(s1) ? 'true' : 'false');
`
**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.
C++ `
#include using namespace std;
// Function to check whether the string // follows the pattern x^n y^n repeatedly bool findPattern(string &s) { int x_count = 0; int y_count = 0;
bool flag = false;
// Traverse the string
for (int i = 0; i < s.length(); i++)
{
// Count consecutive x's
if (s[i] == 'x')
{
x_count++;
}
else
{
// Count consecutive y's
while (i < s.length() && s[i] == 'y')
{
y_count++;
i++;
}
// Move back one step because
// for loop will increment i
i--;
// If counts are equal,
// reset for next block
if (x_count > 0 && x_count == y_count)
{
x_count = y_count = 0;
}
else
{
// Invalid block found
return false;
}
}
}
// Valid only if no invalid block exists
// and both counts become equal
return (x_count == y_count);}
// Driver Code int main() { string s1 = "xxyyxy";
cout << (findPattern(s1) ? "true" : "false") << endl;
return 0;}
Java
import java.util.Scanner;
// Function to check whether the string // follows the pattern x^n y^n repeatedly public class GfG { public static boolean findPattern(String s) { int x_count = 0; int y_count = 0;
boolean flag = false;
// Traverse the string
for (int i = 0; i < s.length(); i++) {
// Count consecutive x's
if (s.charAt(i) == 'x') {
x_count++;
}
else {
// Count consecutive y's
while (i < s.length() && s.charAt(i) == 'y') {
y_count++;
i++;
}
// Move back one step because
// for loop will increment i
i--;
// If counts are equal,
// reset for next block
if (x_count > 0 && x_count == y_count) {
x_count = y_count = 0;
}
else {
return false;
}
}
}
// Valid only if no invalid block exists
// and both counts become equal
return (x_count == y_count);
}
// Driver Code
public static void main(String[] args) {
String s1 = "xxyyxy";
System.out.println(findPattern(s1)? "true" : "false");
}}
Python
Function to check whether the string
follows the pattern x^n y^n repeatedly
def findPattern(s):
i = 0
n = len(s)
# Traverse the string
while i < n:
x_count = 0
y_count = 0
# Count consecutive x's
while i < n and s[i] == 'x':
x_count += 1
i += 1
# Count consecutive y's
while i < n and s[i] == 'y':
y_count += 1
i += 1
# Invalid block
if x_count == 0 or x_count != y_count:
return False
return TrueDriver Code
if name == 'main':
s1 = "xxyyxy"
print("true" if findPattern(s1) else "false")C#
using System;
// Function to check whether the string // follows the pattern x^n y^n repeatedly public class GfG { public static bool findPattern(string s) { int x_count = 0; int y_count = 0;
bool flag = false;
// Traverse the string
for (int i = 0; i < s.Length; i++) {
// Count consecutive x's
if (s[i] == 'x') {
x_count++;
}
else {
// Count consecutive y's
while (i < s.Length && s[i] == 'y') {
y_count++;
i++;
}
// Move back one step because
// for loop will increment i
i--;
// If counts are equal,
// reset for next block
if (x_count > 0 && x_count == y_count) {
x_count = y_count = 0;
}
else {
// Invalid block found
flag = true;
break;
}
}
}
// Valid only if no invalid block exists
// and both counts become equal
return (!flag && x_count == y_count);
}
// Driver Code
public static void Main() {
string s1 = "xxyyxy";
Console.WriteLine(findPattern(s1) ? "true" : "false");
}}
JavaScript
"use strict";
// Function to check whether the string // follows the pattern x^n y^n repeatedly function findPattern(s) { let x_count = 0; let y_count = 0;
let flag = false;
// Traverse the string
for (let i = 0; i < s.length; i++) {
// Count consecutive x's
if (s[i] === 'x') {
x_count++;
}
else {
// Count consecutive y's
while (i < s.length && s[i] === 'y') {
y_count++;
i++;
}
// Move back one step because
// for loop will increment i
i--;
// If counts are equal,
// reset for next block
if (x_count > 0 && x_count == y_count) {
x_count = y_count = 0;
}
else {
// Invalid block found
flag = true;
break;
}
}
}
// Valid only if no invalid block exists
// and both counts become equal
return (!flag && x_count === y_count);}
// Driver Code let s1 = "xxyyxy";
console.log(findPattern(s1) ? "true" : "false");
`
**Time Complexity: O(n)
**Auxiliary Space: O(1)