Check whether two strings are equivalent or not according to given condition
Last Updated :
14 Aug, 2023
Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true:
1) They both are equal. Or,
2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct:
- A1 is recursively equivalent to B1 and A2 is recursively equivalent to B2
- A1 is recursively equivalent to B2 and A2 is recursively equivalent to B1
Check whether given strings are equivalent or not. Print YES or NO.
Examples:
Input : A = "aaba", B = "abaa"
Output : YES
Explanation : Since condition 1 doesn't hold true, we can divide string A into "aaba" = "aa" + "ba" and string B into "abaa" = "ab" + "aa". Here, 2nd subcondition holds true where A1 is equal to B2 and A2 is recursively equal to B1
Input : A = "aabb", B = "abab"
Output : NO
Naive Solution : A simple solution is to consider all possible scenarios. Check first if the both strings are equal return "YES", otherwise divide the strings and check if A1 = B1 and A2 = B2 or A1 = B2 and A2 = B1 by using four recursive calls. Complexity of this solution would be O(n2), where n is the size of the string.
Algorithm
is_recursive_equiv(A, B):
if A == B:
return "YES" // base case: A and B are already equivalent
if length(A) is odd or length(B) is odd:
return "NO" // base case: odd-length strings cannot be recursively equivalent
n = length(A)
A1 = substring(A, 0, n/2) // divide A into two halves
A2 = substring(A, n/2)
B1 = substring(B, 0, n/2) // divide B into two halves
B2 = substring(B, n/2)
if (is_recursive_equiv(A1, B1) == "YES" and is_recursive_equiv(A2, B2) == "YES") or
(is_recursive_equiv(A1, B2) == "YES" and is_recursive_equiv(A2, B1) == "YES"):
return "YES" // if corresponding halves are recursively equivalent, return "YES"
return "NO" // otherwise, return "NO"
Implementation of above approach
C++
#include <iostream>
#include <string>
using namespace std;
string is_recursive_equiv(string A, string B) {
// Check if A and B are already equivalent
if (A == B) {
return "YES";
}
// Check if the length of A and B is even
if (A.length() % 2 != 0 || B.length() % 2 != 0) {
return "NO";
}
// Divide A and B into two halves
int n = A.length();
string A1 = A.substr(0, n/2);
string A2 = A.substr(n/2);
string B1 = B.substr(0, n/2);
string B2 = B.substr(n/2);
// Recursively check if the halves of A and B are equivalent
if ((is_recursive_equiv(A1, B1) == "YES" && is_recursive_equiv(A2, B2) == "YES") ||
(is_recursive_equiv(A1, B2) == "YES" && is_recursive_equiv(A2, B1) == "YES")) {
return "YES";
}
return "NO";
}
int main() {
string A = "aaba";
string B = "abaa";
cout << is_recursive_equiv(A, B) << endl; // Output: YES
A = "aabb";
B = "abab";
cout << is_recursive_equiv(A, B) << endl; // Output: NO
return 0;
}
Java
import java.util.*;
public class Main {
static String isRecursiveEquiv(String A, String B) {
// Check if A and B are already equivalent
if (A.equals(B)) {
return "YES";
}
// Check if the length of A and B is even
if (A.length() % 2 != 0 || B.length() % 2 != 0) {
return "NO";
}
// Divide A and B into two halves
int n = A.length();
String A1 = A.substring(0, n / 2);
String A2 = A.substring(n / 2);
String B1 = B.substring(0, n / 2);
String B2 = B.substring(n / 2);
// Recursively check if the halves of A and B are equivalent
if ((isRecursiveEquiv(A1, B1).equals("YES") && isRecursiveEquiv(A2, B2).equals("YES"))
|| (isRecursiveEquiv(A1, B2).equals("YES") && isRecursiveEquiv(A2, B1).equals("YES"))) {
return "YES";
}
return "NO";
}
public static void main(String[] args) {
String A = "aaba";
String B = "abaa";
System.out.println(isRecursiveEquiv(A, B)); // Output: YES
A = "aabb";
B = "abab";
System.out.println(isRecursiveEquiv(A, B)); // Output: NO
}
// This code is contributed by Shivam Tiwari.
}
Python
def is_recursive_equiv(A, B):
if A == B:
return "YES"
if len(A) % 2 != 0 or len(B) % 2 != 0:
return "NO"
n = len(A)
A1, A2 = A[:n//2], A[n//2:]
B1, B2 = B[:n//2], B[n//2:]
if (is_recursive_equiv(A1, B1) == "YES" and is_recursive_equiv(A2, B2) == "YES") or \
(is_recursive_equiv(A1, B2) == "YES" and is_recursive_equiv(A2, B1) == "YES"):
return "YES"
return "NO"
A = "aaba"
B = "abaa"
print(is_recursive_equiv(A, B)) # Output: YES
A = "aabb"
B = "abab"
print(is_recursive_equiv(A, B)) # Output: NO
C#
using System;
class Program
{
static string IsRecursiveEquiv(string A, string B)
{
// Check if A and B are already equivalent
if (A == B)
{
return "YES";
}
// Check if the length of A and B is even
if (A.Length % 2 != 0 || B.Length % 2 != 0)
{
return "NO";
}
// Divide A and B into two halves
int n = A.Length;
string A1 = A.Substring(0, n/2);
string A2 = A.Substring(n/2);
string B1 = B.Substring(0, n/2);
string B2 = B.Substring(n/2);
// Recursively check if the halves of A and B are equivalent
if ((IsRecursiveEquiv(A1, B1) == "YES" && IsRecursiveEquiv(A2, B2) == "YES") ||
(IsRecursiveEquiv(A1, B2) == "YES" && IsRecursiveEquiv(A2, B1) == "YES"))
{
return "YES";
}
return "NO";
}
static void Main()
{
string A = "aaba";
string B = "abaa";
Console.WriteLine(IsRecursiveEquiv(A, B)); // Output: YES
A = "aabb";
B = "abab";
Console.WriteLine(IsRecursiveEquiv(A, B)); // Output: NO
}
}
JavaScript
// Function to check if two strings A and B are recursively equivalent
function isRecursiveEquiv(A, B) {
// Check if A and B are already equivalent
if (A === B) {
return "YES";
}
// Check if the length of A and B is even
if (A.length % 2 !== 0 || B.length % 2 !== 0) {
return "NO";
}
// Divide A and B into two halves
const n = A.length;
const A1 = A.substring(0, n / 2);
const A2 = A.substring(n / 2);
const B1 = B.substring(0, n / 2);
const B2 = B.substring(n / 2);
// Recursively check if the halves of A and B are equivalent
if (
(isRecursiveEquiv(A1, B1) === "YES" && isRecursiveEquiv(A2, B2) === "YES") ||
(isRecursiveEquiv(A1, B2) === "YES" && isRecursiveEquiv(A2, B1) === "YES")
) {
return "YES";
}
return "NO";
}
// Test cases
const A1 = "aaba";
const B1 = "abaa";
console.log(isRecursiveEquiv(A1, B1)); // Output: YES
const A2 = "aabb";
const B2 = "abab";
console.log(isRecursiveEquiv(A2, B2)); // Output: NO
Efficient Solution : Let's define following operation on string S. We can divide it into two halves and if we want we can swap them. And also, we can recursively apply this operation to both of its halves. By careful observation, we can see that if after applying the operation on some string A, we can obtain B, then after applying the operation on B we can obtain A. And for the given two strings, we can recursively find the least lexicographically string that can be obtained from them. Those obtained strings if are equal, answer is YES, otherwise NO. For example, least lexicographically string for "aaba" is "aaab". And least lexicographically string for "abaa" is also "aaab". Hence both of these are equivalent.
Steps to follow to implement the above approach:
- Define a function leastLexiString(s) that takes a string s as input and returns the least lexicographical string that can be formed by rearranging the letters of s.
- If the length of s is odd, return s as it is. This is the base case.
- Divide the string s into two halves, x and y.
- Recursively call leastLexiString() on x and y to find the least lexicographical strings that can be formed from these two halves.
- return min(x+y,y+x).
- Define a function areEquivalent(a, b) that takes two strings a and b as input and returns true if the least lexicographical strings that can be formed from a and b are equal, false otherwise.
- Call leastLexiString() on a and b, and compare the results. If they are equal, return true, otherwise return false.
Below is the code to implement the above approach:
C++
// CPP Program to find whether two strings
// are equivalent or not according to given
// condition
#include <bits/stdc++.h>
using namespace std;
// This function returns the least lexicogr
// aphical string obtained from its two halves
string leastLexiString(string s)
{
// Base Case - If string size is 1
if (s.size() & 1)
return s;
// Divide the string into its two halves
string x = leastLexiString(s.substr(0,
s.size() / 2));
string y = leastLexiString(s.substr(s.size() / 2));
// Form least lexicographical string
return min(x + y, y + x);
}
bool areEquivalent(string a, string b)
{
return (leastLexiString(a) == leastLexiString(b));
}
// Driver Code
int main()
{
string a = "aaba";
string b = "abaa";
if (areEquivalent(a, b))
cout << "YES" << endl;
else
cout << "NO" << endl;
a = "aabb";
b = "abab";
if (areEquivalent(a, b))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
Java
// Java Program to find whether two strings
// are equivalent or not according to given
// condition
class GfG
{
// This function returns the least lexicogr
// aphical String obtained from its two halves
static String leastLexiString(String s)
{
// Base Case - If String size is 1
if (s.length() == 1)
return s;
// Divide the String into its two halves
String x = leastLexiString(s.substring(0,
s.length() / 2));
String y = leastLexiString(s.substring(s.length() / 2));
// Form least lexicographical String
return String.valueOf((x + y).compareTo(y + x));
}
static boolean areEquivalent(String a, String b)
{
return !(leastLexiString(a).equals(leastLexiString(b)));
}
// Driver Code
public static void main(String[] args)
{
String a = "aaba";
String b = "abaa";
if (areEquivalent(a, b))
System.out.println("Yes");
else
System.out.println("No");
a = "aabb";
b = "abab";
if (areEquivalent(a, b))
System.out.println("Yes");
else
System.out.println("No");
}
}
/* This code contributed by PrinciRaj1992 */
Python3
# Python 3 Program to find whether two strings
# are equivalent or not according to given
# condition
# This function returns the least lexicogr
# aphical string obtained from its two halves
def leastLexiString(s):
# Base Case - If string size is 1
if (len(s) & 1 != 0):
return s
# Divide the string into its two halves
x = leastLexiString(s[0:int(len(s) / 2)])
y = leastLexiString(s[int(len(s) / 2):len(s)])
# Form least lexicographical string
return min(x + y, y + x)
def areEquivalent(a,b):
return (leastLexiString(a) == leastLexiString(b))
# Driver Code
if __name__ == '__main__':
a = "aaba"
b = "abaa"
if (areEquivalent(a, b)):
print("YES")
else:
print("NO")
a = "aabb"
b = "abab"
if (areEquivalent(a, b)):
print("YES")
else:
print("NO")
# This code is contributed by
# Surendra_Gangwar
C#
// C# Program to find whether two strings
// are equivalent or not according to given
// condition
using System;
class GFG
{
// This function returns the least lexicogr-
// aphical String obtained from its two halves
static String leastLexiString(String s)
{
// Base Case - If String size is 1
if (s.Length == 1)
return s;
// Divide the String into its two halves
String x = leastLexiString(s.Substring(0,
s.Length / 2));
String y = leastLexiString(s.Substring(
s.Length / 2));
// Form least lexicographical String
return ((x + y).CompareTo(y + x).ToString());
}
static Boolean areEquivalent(String a, String b)
{
return !(leastLexiString(a).Equals(
leastLexiString(b)));
}
// Driver Code
public static void Main(String[] args)
{
String a = "aaba";
String b = "abaa";
if (areEquivalent(a, b))
Console.WriteLine("YES");
else
Console.WriteLine("NO");
a = "aabb";
b = "abab";
if (areEquivalent(a, b))
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript Program to find whether two strings
// are equivalent or not according to given
// condition
// This function returns the least lexicogr-
// aphical String obtained from its two halves
function leastLexiString(s)
{
// Base Case - If String size is 1
if (s.length == 1)
return s;
// Divide the String into its two halves
let x = leastLexiString(s.substring(0,
s.length / 2));
let y = leastLexiString(s.substring(
s.length / 2));
// Form least lexicographical String
if((x + y) < (y + x))
{
return (x+y);
}
else{
return (y+x);
}
}
function areEquivalent(a, b)
{
return (leastLexiString(a) == leastLexiString(b));
}
let a = "aaba";
let b = "abaa";
if (areEquivalent(a, b))
document.write("YES" + "</br>");
else
document.write("NO" + "</br>");
a = "aabb";
b = "abab";
if (areEquivalent(a, b))
document.write("YES" + "</br>");
else
document.write("NO" + "</br>");
// This code is contributed by decode2207.
</script>
PHP
<?php
// PHP Program to find whether two strings
// are equivalent or not according to given
// condition
// This function returns the least lexicogr
// aphical string obtained from its two halves
function leastLexiString($s)
{
// Base Case - If string size is 1
if (strlen($s) & 1)
return $s;
// Divide the string into its two halves
$x = leastLexiString(substr($s, 0,floor(strlen($s) / 2)));
$y = leastLexiString(substr($s,floor(strlen($s) / 2),strlen($s)));
// Form least lexicographical string
return min($x.$y, $y.$x);
}
function areEquivalent($a, $b)
{
return (leastLexiString($a) == leastLexiString($b));
}
// Driver Code
$a = "aaba";
$b = "abaa";
if (areEquivalent($a, $b))
echo "YES", "\n";
else
echo "NO", "\n";
$a = "aabb";
$b = "abab";
if (areEquivalent($a, $b))
echo "YES", "\n";
else
echo "NO","\n";
// This code is contributed by Ryuga
?>
Time Complexity: O(N*logN), where N is the size of the string.
Auxiliary Space: O(logN)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem